Search

Spring Multi Action Controller Tutorial / Example

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 theUserController 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="0" encoding="UTF-8"?>

<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 theremove() method.
<a href="user/add.htm" >Add</a>

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

No comments:

Post a Comment