Meyyappan has posted 101 posts at DZone. View Full User Profile

Spring MultiActionController Tutorial

06.15.2012
| 30217 views |
  • submit to reddit

Using Spring MultiActionController class you can group related actions into a single controller class. The handler method for each action should be in the following form.

public (ModelAndView | Map | String | void) actionName(HttpServletRequest, HttpServletResponse [,HttpSession] [,CommandObject]);

 To group multiple actions your controller class should extend MultiActionController class. Here the UserController class extends the MultiActionController class and contains the add() and the remove() method as shown below.

package com.vaannila.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction. MultiActionController;

public class UserController extends MultiActionController {
	
	public ModelAndView add(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		System.out.println("Add method called");
		return new ModelAndView("user", "message", "Add method called");
	}
	
	public ModelAndView remove(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		System.out.println("Remove method called");
		return new ModelAndView("user", "message", "Remove method called");
	}
}

Here we use the BeanNameUrlHandlerMapping to map the request url. The Spring bean configuration file is shown below.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="viewResolver" class="org.springframework.web.servlet.view. InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
	    
	<bean name="/user/*.htm" class="com.vaannila.web.UserController" />

</beans>

So to map multiple actions, we use the asterisk character. Anything that matches the asterisk character will be considered as the method name in the UserController class.

In the redirect.jsp page we have two urls one to call the add() method and the other to call the remove() method.

<a href="user/add.htm" >Add</a> <br>
<a href="user/remove.htm" >Remove</a>

 You can download and try the example here.

Source :Download
War :Download
Published at DZone with permission of its author, Meyyappan Muthuraman.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: