Spring MultiActionController Example

MultiActionController is one of the types of Controllers in Spring. It extends AbstractController. (Somewhat similar to DispatchAction in Struts)  Why MultiActionController?: It aggregates multiple request handling methods into single controller, so related functionality can be kept together easily.
NOTE:To reduce complexity, I have added business logic in Controller. Later on I will republish this example as per MVC2 standards. Let’s go through the flow of application.

Initially index.jsp is viewed to user,

index.jsp

<html>
 <head>
 </head>
 <body>
 <h3> Spring Demo </h3>
 <h4>1) Enter 'abc' as FirstName and 'xyz' as LastName for successful login
attempt. All other combinations will fail.</h4>
 <form action="validate.process" method="post">
 First Name:<input type="text" name="firstName" />
 Last Name:<input type="text" name="lastName" />
 <input type="submit" value="Sign In"/>
 </form>
 <h4>2)</h4>
 Click <a href="sayHello.do">here</a> to get 'Hello' Message.
 </body>
</html>

When submit button is pressed or hyperlink is clicked flow will go to WEB.XML from index.jsp

WEB.XML

<web-app>
<!-- Below is Spring DispatcherServlet that is configured with
FrontControllerServlet-servlet.xml -->

 <servlet>
 <servlet-name>FrontControllerServlet</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>FrontControllerServlet</servlet-name>
 <url-pattern>*.process</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
 <servlet-name>FrontControllerServlet</servlet-name>
 <url-pattern>*.do</url-pattern>
 </servlet-mapping>

 <welcome-file-list>
 <welcome-file>index.do</welcome-file>
 </welcome-file-list>

</web-app>

WEB.XML instructs that, ‘*.do and *.process URLs are served by FrontControllerServlet. FrontControllerServlet is internally instantiated with the configuration file FrontControllerServlet-servlet.xml. (Remember Spring naming convention for DispatcherServlet configuration XML is ‘<DispatcherServlet name>-servlet.xml’)

FrontControllerServlet-servlet.xml

<beans>

 <!--TO MAP URL TO PROPER CONTROLLER, use 'SimpleUrlHandlerMapping' as below.
        (CONTROLLER CAN BE MultiAction/SimpleForm/UrlFilenameView etc.)
 -->
 <bean id="urlHandler"
   class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" >
 <property name="mappings">
 <map>
 <entry key="/validate.process" value="multiActionController"/>
 <entry key="/sayHello.do" value="multiActionController"/>
 <entry key="/index.do" value="multiActionController"/>
 </map>
 </property>
 </bean>

 <!-- BELOW IS A REFERENCE TO A CLASS THAT EXTENDS
 org.springframework.web.servlet.mvc.multiaction.MultiActionController
 & ABLE TO HANDLE MULTIPLE DIFFERENT REQUESTS WITH THE HELP OF
 PropertiesMethodNameResolver CLASS
 -->
 <bean id="multiActionController" class="controller.MyController" >
 <property name="methodNameResolver" ref="myResolver" /> </bean>

 <!-- BELOW CLASS WILL MAP INCOMING URL TO METHOD OF MultiActionController -->
 <bean id="myResolver"
 class="org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver"
 lazy-init="default">
 <property name="mappings">
 <props>
 <prop key="/validate.process">validateLogin</prop>
 <prop key="/index.do">goToHome</prop>
 <prop key="/sayHello.do">sayHello</prop> </props>
 </property>
 </bean>

</beans>

Inside FrontControllerServlet, Request is given to ‘SimpleUrlHandlerMapping bean’ initially. There request is routed to proper controller bean. In our case *.do and *.process are routed to controller.MyController (extends MultiActionController) bean. Before request goes to MyController, request has to find out proper method that can serve it. Look at ‘PropertiesMethodNameResolver bean’, it maps URL to proper method inside our MultiActionController. Now, request is handed over to controller.MyController class,

controller.MyController.java

package controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
/**
* @author Gaurang Patel
*/
public class MyController extends MultiActionController {
/**
* LOGIN IS SUCCESSFUL ONLY IF FIRSTNAME='abc' and LASTNAME='xyz'.
* YOU CAN DEFINE HERE PROPER BUSINESS LOGIC FOR LOGIN.
*/

 public ModelAndView validateLogin(HttpServletRequest request,
 HttpServletResponse response){
 String firstName = request.getParameter("firstName");
 String lastName = request.getParameter("lastName");

 if(firstName.equals("abc") && lastName.equals("xyz"))
 return new ModelAndView("loginSuccess.jsp");
 else
 return new ModelAndView("loginFailure.jsp");
 }
 public ModelAndView sayHello(HttpServletRequest request,
 HttpServletResponse response){
 return new ModelAndView("sayHello.jsp");
 }
 public ModelAndView goToHome(HttpServletRequest request,
 HttpServletResponse response){
 return new ModelAndView("index.jsp");
 }

}

Here MyController does proper business logic and route request to its relevant JSP and eventually JSP is displayed back to User. (Ideally MyController is not supposed to route request to directly JSP as per MVC2 but to reduce complexity, I have used.) Check out below JSP pages,

loginSuccess.jsp

<html>
<head>
</head>
<body>
<a href="index.do">HOME</a>
<h3>Welcome.. Login attempt was successful..</h3>
</body>
</html>

loginFailure.jsp

<html>
<head>
</head>
<body>
<a href="index.do">HOME</a>
<h3>Login attempt failed..</h3>
</body>
</html>

sayHello.jsp

<html>
<head>
</head>
<body>
<a href="home.do">HOME</a>
<h3>Hello......</h3>
</body>
</html>

Food For Thoughts:

Have you observed sayHello/goToHome methods of MyController.java? Here, we don’t need any business logic for processing request. In short, we are just returning a static resource to user, nothing else. Then it is overhead to propagate request to Controller, isn’t it?

Spring’s one of the answer to this is ‘UrlFilenameViewController’. This controller allows you to directly map request against resource in XML itself. No need to go to Controller class like MyController.java in above case. I will post ‘UrlFilenameViewController’example in few days. Keep Checking…

Download this working example source code here.

Related Posts

Spring UrlFilenameViewController Example

Spring MVC Application Flow With Diagram

Ideal Way Of Exception Handling In Multi Layer Java Web Application

Reliance NetConnect: How To Get 45% Discount On Existing Postpaid Plan

19 Comments

  1. Ritesh

    11.24.2009

    cooooolll!! It saved my day… thanx

  2. Priya

    12.16.2009

    hi Gaurang,

    You have not mentioned how we do binding ? The data will be lost between page callbacks ?

    -P

  3. Gaurang

    12.16.2009

    Priya,
    It is not necessary to map text fields with variables in Java file..

    To concentrate on core, ‘multiActionControl’ functionality, I haven’t used that one.

    So, by default, It will come as a parameter along with HttpServletRequest, a plain JSP fundamental.

    Data will not be lost and simply I can retrieve it by calling ‘request.getParameter(“..”)’.

    Try it..

    Hope I have answered your question.

  4. Gaurang

    12.17.2009

    Let me add one more point for above question,,

    When I want some data from Controller to JSP/ModelClass, I have to use one of the below overloaded ‘ModelAndView Constructor’,

    ModelAndView(String viewName, Map model) OR ModelAndView(String viewName, String modelName, Object modelObject) etc..
    —————
    In our example context, let me rewrite one method

    public ModelAndView goToHome(…){
    return new ModelAndView(“index.jsp”,”abc”, new Object() );
    }

    Then in ‘index.jsp’, I can say ‘request.getAttribute(“abc”)’ & it will return me object instance created in goToHome(..) method.

  5. Priya

    12.23.2009

    Hi Gaurang,

    Thanks for your reply. I accept that the data is not lost. How can we display error messages ? Do I need to check each parameter through “request.getAttribute()” and display error message ?

  6. Priya

    12.24.2009

    hi Gaurang,

    Could you please update me about the validation errors display issue. I will appreciate all your help.

    Thanks.

  7. Chris

    01.14.2010

    Hi,
    Is that possible to user referenceData() (or something similar) in order to pass lookup lists to insert/update forms?
    It is supported by SimpleFormController and AbstractWizzardFormController, but I didn’t find anything about MultiactionController.

  8. Gaurang Patel

    02.02.2010

    @Priya,
    I’m bit late. Sorry. In fact I have published one article related to your query regarding validation error display issue. Please check http://www.goospoos.com/2010/02/ideal-way-of-exception-handling-in-multi-layer-java-web-application/
    I hope you will get answer over there..

    @Chris,
    Yet I haven’t come across this thing but I will let you in case of finding solution.

  9. jit

    03.01.2010

    Hi Gaurang,
    I want to use MultiActionController in my existing spring web application. The current application is having individual controllers for say list, add,edit,delete. So i though of using MultiActionController. In this scenario the individual controllers takes some properties which are configured through my …-context.xml as follows

    1

    2

    3

    4

    5

    In order to use MultiActionController how to pass the above properties so that for one action 2 properties passed and for another action 3 properties are passed.

    Thanks

  10. kumar

    03.11.2010

    Can you please give me one example for , form with number of buttons(add,remove,update). In this case how MultiActionContrlooer is working.

  11. RKH

    07.19.2010

    Thanks a lot!

  12. Parshuram

    08.20.2010

    Can you please give me one example for , form with number of buttons(add,remove,update). In this case how MultiActionContrlooer is working.

  13. saurabh sharma

    12.26.2010

    Hi !Gaurang,
    there are two or more form on my jsp. i want to validate those form, using multicontroller how can i validate these form ! in SimpleFormController it is possible easy, how in MultiActionController

  14. Kranthi M

    01.03.2011

    Hi,

    I am trying to run this app in Jboss environment.but when I try to run index.jsp on server it is throwing an exception.

    GlobalNetPOC is my project name and index.jsp in webcontent folder.

    What should be the url I ahve to satrt with?

    I am getting GlobalNetPOC/index.do resource not found error.

    Can you please help on this…

  15. sumwin

    03.24.2011

    glad 2 see this post..thnxxxxxx :)

  16. sumwin

    03.24.2011

    waitin 4 urlFilenameViewController…….

  17. Vaibhav

    05.12.2011

    Hi Gaurang,

    I am not ablr to read commandbean attributes in action class (MultiActionController) .

    **
    personalEntryList is my commandbean.
    **
    public ModelAndView removeQuickFixWantList(HttpServletRequest request , HttpServletResponse response ,PersonalEntryList personalEntryList ){

    Sysout(personalEntryList.getName()); // Throwing Null pointer exception .
    }

    —————————————-
    i have mentioned following tag in my jsp

  18. suraj

    08.24.2011

    Every body talk about MultiActionController example.But no body talks about validation with MultiActionController.

    If u can ,please send me the sample app to my mail.

    Work will be always appreciated

  19. Anshul Agarwal

    11.28.2011

    Could you please give an example of validations in MultiAction Controller.

Leave a Reply









Tags

Ad

Like Us!