Spring MVC Flow with example

In this article, learn the Spring MVC Flow with example. Spring MVC is mostly used with Spring for any web application development. It is very powerful and nice layered architecture for flow and configuration. It is very flexible to integrate with other web frameworks.

Spring MVC Flow:-

1. Dispatcher servlet takes the incoming request.

2. Dispatcher servlet contacts the Handle Mapping with incoming request URL(/cource.xadmin)

3. Handler mapping identifies and returns the controller (course controller) specified for the request URL.(/cource.xadmin)

4. Dispatcher servlet identifies and invokes one or more handler interceptors registered with spring container if any then dispatcher servlet invokes the controller i.e,
handlerRequestInternal() method of CourseController -with XML
getCourse() method of CourseController -with Annotation

5. After finishing the controller method execution, all the registered handler interceptions will be called in the reverse order one by one. Finally, DispatcherServlet gets ModelAndView class object (which contains view logical name and model data). Finally, DispatcherServlet gets the view logical name.

6 DispatcherServlet contacts the viewResolver with the view logical name( show).

7. DispatcherServlet gets the view (/show.jsp) from viewResolver.

8.DispatcherServlet forwards the identified view(/show.jsp) to the client.

Simple login example using spring MVC with XML configuration.
Files required

index.jsp login.jsp
Home.jsp LoginController.java
User.java UserValidator.java
Messages.properties Web.xml
Xadmin-servlet.xml

Index.jsp

<html> 
<body>
<br><h1> Xadmin website<br/>
<a href=”<c:url value=”course.jtc”/>”> show Xadmin Cource</a>
</h1> </body></html>

Login.jsp

<html> 
<body>
<center>
<h1> Xadmin Account login </h1>
<form:form method=”post” commandName=”user”>
<table>
<tr> <id> Username</id>
<td><from:input path=”username”/></td>
<td><font color=red size=5>
<form:errors path=”username”></font></td></tr>
<tr><td>password</td>
<td><form:password</td>
<td><form:password path=”password”/></td>
<td><font color=red size=5>
<form:errors path=”password”/></font></td></tr>
</table>
<br> <input type=”submit” value=”Account Login”>
</form:form>
</center></body></html>

Home.java

<%@ taglib prefix=”c” uri=http://java.sun.com/jsp/jstl.core%>
<html><body>
<h1> Hi ${user.username}; Your Login Successful </h1>
<h1> this is you home page</h1>
</body> </html>

LoginController.java

package com.xadmin.spring.mvc;
import org.springframework.validation.BindException;
Import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.simpleformController;
import javax.servlet.servletException
import javax.servlet.http.*;

public class LoginController extends simpleFormController {
public modelandviewonSubmit(Object command, BindException errors) throws servletException {
System.out.println(“in onSubmit()”);
User user= (user)command;
String un=user.getusername();
String pw=user.getPassword();
String view=””;
if(un.equals(uw)) {
view=getFormView();
}
return new modelAndView (view,”user”, user);
}
public object formBacking object(HttpServletRequest request) throws servletException
{
System.out.println(“in form BackingOBject()”);
User user= new user();
User.setUsername(“Ashish Bhagat”);
return user;
}
}

User.java

package com.xadmin.spribng.mvc;
public class user {
private string username;
private string password;
//setter and getters
}

UserValidator.java

package com.xadmin.spribng.mvc;
import org.springframework.validation.*;

public class userValidation implements validation {
public Boolean supports(class clazz)
{
return user.class.equals(clazz);
}

public void validate(object command. Errors errors)
{
User user=(user) Command;
If(user.getUsername()==null || User.getUsername().length()==0)
{
errors.rejectValue(“username”, “error.username.required”, null,”Username required”);
}
if(user.getPassword()== null || user.getPassword.length() ==0) 
{
errors.rejectValue(“password”, “error.password.required”, null, “password required”);
}
}

Message.properties

Eorror.Username.required=username is mandatory
Error.password.required=password is mandatory

xadmin-servlet.xml

<beans .......
<context:annotation-config/>
  class=”org.spring.framework.web.servlet.view.InternalResourceViewResolver”>
  <property name=”viewclass”
    value=”org.springframework.web.servlet.view.internalResourceView”/>
  <property name=”prefix” value”/”/>
  <property name=”suffix” value”jsp”/>
</bean>

<bean name=”/login.xadmin” class=”com.xadmin.spring.mvc.coursecontroller”/>

<property name=”sessionForm” value=”true”/>
<property name=”commandName” value=”user”/>
<property name=”commandclass” value=”com.xadmin.spring.mvc.user”/>
<property name=”validator”>

<bean class=com.xadmin.spring.mvc.userValidator”/>
</property>

<property name=”formView” value=”login”/>
<property name=”successView” value=”home”/>
</bean>
<bean id=”messageSource” class=”org.springframework.context.support.ResourceBundleMessageSource”>
<property name=”basename” value=”messages”/>
</bean>
</beans>

Spring MVC Request processing flow (with XML)
When you request for a resource(JSP or View)  the following tasks will happen:

  1. Dispatcher servlet takes the incoming request.
  2. Dispatcher Servlet contacts the handler Mapping with incoming request URL (/cource.xadmin)
  3. Handler Mapping returns the controller(LogicController) specified for the requested Url(/cource.xadmin)
  4. Dispatcher servlet gets the form view property value(login)
  5. Dispatcher servlet contacts the view Resolver with the view logical name (login)
  6. Dispatcher servlet gets the view (/login.jsp) for the view resolver.
  7. Dispatcher servlet checks whether identified view (/login.jsp) contains <form:form> tag or not.
  8. If identified view(/login.jsp) doesnot contains <form : form> tag then that view will be forwarded for the client.
  9. If identified view(/login.jtc) contains <form : form> tag then Dispatcher servlet invokes the controller method Object obj= ic.formBackingObject(request);
  10. Dispatcher servlet gets the command object returned by formBacking object() method.
  11. Dispatcher servlet gets data from command object by calling getter methods on command object and populates that into the corresponding fields of the JSP form.
  12. Dispatcher servlet forwards the identified view (/login.jsp) to the client.

When you send the request by submitting a form, the following tasks will happen:

  1. DispatcherServlet takes the incoming request.
  2. DispatcherServlet contacts the Handler mapping with incoming request URL(/login.xadmin)
  3. Handler Mapping return the controller (LogicController) specified for the request URL(/logic.xadmin)
  4. DispatcherServlet populates client submitted data.
  5. DispatcherServlet populates clients submitted data into a command object by calling setter methods.
  6. DispatcherServlet creates the errors object
  7. DispatcherServlet invokes the validate() method by passing the command object and errors object. uv.validate(command.errors);
  8. DispatcherServlet checks whether errors object contains any errors.
  9. If error found the dispatcherServletgets the form view property value(login) and goes to step 12.
  10. if no error found foundthe dispatcherServlet invokes the controller method a.methodAndView Mav=cl.onSubmit(Command);
  11. DispatcherServlet get the modelandview class object( which contains view logical name and model data);
  12. DispatcherServlet contacts the viewResolver with the view logical name(lofgin from STEP 9 or home from STEP 11)
  13. DispatcherServlet gets the view(/home.jsp or .login.jsp)
  14. DispatcherServlet forwards the identified view (/home.jsp or /login.jsp) to the client.

Login Example using spring MVC with XML configuration.
File required

Index.jsp Login.jsp
Home.jsp LoginController.java
User.java UserValidator.java
Message.properties Web.xml
Xadmin-servlet.xml

Login.jsp

<%@ taglib prefix=”form” uri=http://www.springframework.org/tags/form%>
<html><body><center>
<h1>User Account Login</h1>
<form:form action=”verifyUser.xadmin” method=”post” commandName=”user”>
</center></body></html>

LoginController.java

package com.xadmin.spring.mvc;

import java.util.map;
import org.springframework.beansfactory.annotation.Autowired.
Import org.springframework.stereotype.controller;
import org.spring.framework.validation.bindingResult;
import org.sprinmgframework.web.bind.annotation.*;
import javax.servlet.servletException;

@Controller
@SessionAttributes
public class LoginController {

@Autowired
private userValidator userValidator;

@RequestMapping( value=”/verfyUser”, method=requestMethod.Post)
Public string [email protected](“user”)
User user, Binding Result Result result)
{
System.out.println(“verifyUser()”);
userValidator.validator(user,result);
if(result.hasErrors())
{
System.out.println(result.getErrorCount());
return “login”;
}
// User user=(user) command;
String un=user.getUsername();
String pw=user.getPassword();

System.out.println(un);
System.out.println(pw);
if(!um.equals(pw))
{
return “login”;
}
return “home”;
}

@RequestMapping(“/login”)
public string showLoginForm(Map model) throws servletException {
System.out.println(“showLoginForm”);
User user= new User(0;
user.setUsername(“Ashish Bhagat”);
model.put(“user”,user);
retun “login”;
}
}

xadmin-servlet.xml

<beans .......
<context:annotation-config/>
  class=”org.spring.framework.web.servlet.view.InternalResourceViewResolver”>
  <property name=”viewclass”
    value=”org.springframework.web.servlet.view.internalResourceView”/>
  <property name=”prefix” value”/”/>
  <property name=”suffix” value”jsp”/>
</bean>

<bean name=”/cource.xadmin” class=”com.xadmin.spring.mvc.coursecontroller”/>
<bean id=”cs” class=”com.xadmin.spring.mvc.courseService”/>
<beans>

Spring MVC request processing flow(with Annotation)
When you request for a resource (JSP or view), the following tasks will happen:

  1. DispatcherServlet takes the incoming request.
  2. DispatcherServlet t contacts the Handler mapping with incoming request URL(/login.xadmin)
  3. Handler Mapping return the controller (LogicController) specified for the request URL(/logic.xadmin)
  4. Dispatcher servlet creates the Map object. Map model= new HashMap();
  5. Dispatcher servlet invokes the controller method.
  6. Dispatcher servlet gets the view logical name(login) from the controller method.
  7. Dispatcher servlet contacts the view resolver with the view logical name (login).
  8. Dispatcher servlet gets the view(/login/jsp) from view resolver
  9. Dispatcher servlet checks whether identified view(/login.jsp) contains <form:form> tag or not.
  10. If identified view (/login.jsp) does not contain <form:form> tag then that view will be forwarded to client.
  11. If identified view (/login.jsp) contains <form:form>tag then Dispatcher servlet collects the model attribute (which is the command object) from the Map.
  12. Dispatcher servlet gets data from command object by calling by getter methods on command object and populates that into the corresponding fields of the JSP form.
  13. Dispatcher servlet forwards the identified view (/login.jsp) to the client.

When you send the request by submitting a form, the following tasks will happen:

  1. DispatcherServlet takes an incoming request.
  2. Dispatcher Servlet contacts the handler mapping with incoming request URL(/verifyUser.xadmin);
  3. Handler Mapping return the controller (logic controller) and the corresponding method of the controller-with specified for the request URI(/verifyUSer.xadmin)
  4. Dispatcher Servlet collects the model attributes (which is the command object) from the Map User user=(user)model.get(“user”);
  5. Dispatcher Servlet collects client submitted data.
  6. Dispatcher servlet populates client submitted data into command object by calling setter methods
  7. Dispatcher servlet creates the BindingResult object.
  8. DispatcherServlet invokes the controller method(verfiyUser()) by passing command and BindingResult objects
  9. Dispatcher Servlet gets the string object which is the view logical name
  10. Dispatcher servlet contacts the view Resolver with the view logical name.
  11. Dispatcher servlet gets the view (/home.jsp or .logic.jsp)
  12. Dispatcher Servlet forwards the identified view (/home.jsp or /login.jsp) to the client.

Conclusion: 
In this article of Spring MVC Flow, you’ve gone through the processing of a request in the Spring MVC framework in detail with example. please feel free to drop a comment in the comment box below if you have a doubt regarding the topic or you want to share more information about the topic. Happy Learning!