Spring MVC Tutorial with Examples

Model view controller is a software architecture design pattern.  It provides solution to layer an application by separating three concerns business, presentation and control flow.
  • The Model can be some DAO layer or some Service Layers which give some information about request or requested information or Model can be a POJO which encapsulates the application data given by the controller.
  • The View is responsible for rendering the model data and in general it generates HTML output that the client's browser can interpret.
  • The Controller is responsible for processing user requests and building appropriate model and passes it to the view for rendering.
Spring MVC Tutorial


Advantages of Spring MVC Framework-
  • Supports RESTful URLs.
  • Annotation based configuration(i.e. you may reduce the metadata file or less of configuration).
  • Supports to plug with other MVC frameworks like Struts, Struts2, WebWorks etc.
  • Flexible in supporting different view types like JSP, velocity, XML, PDF, Tiles etc.
Front Controller: Front Controller is very important component one which route the all the requests into framework control that means when ever requests land on different controllers it queues that request to the controller of framework without this MVC framework will not may be able to take control of the request at landing at the application. So front controller is not only capture the request but also the following responsibility-
  • It initialize the framework to cater to the requests.
  • Load the map of all URLs and the components responsible to handle the request.
  • Prepare the map for the views.  
Spring MVC FrontController

Spring 3 MVC Basic Architecture:
The Spring web MVC framework provides model-view-controller architecture and ready components that can be used to develop flexible and loosely coupled web applications. The MVC pattern results in separating the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements.
Spring MVC Basic

In Spring 3 MVC framework Dispatcher Servlet access Front Controller which handles all coming requests and queses for forward to the different controller. 
1. Whenever request lands the dispatcher servlet consult with HandlerMapping 
(HandlerMapping- is a component which have the map of URL and Controller which need to be invoked for that particular request which lands with URL) 
2. then Dispatcher servlet has information about which is controller need to be invoked 
3. then that controller will be invoked 
4. and Controller can request the model for some information (about some DAO, Service layer or Data in POJO, or data in database using business logic) 
5. once process has been done then dispatcher servlet get the response then dispatcher servlet will get view resolver to build the view and view resolver look out what view has being configured it has been JSP, Velocity, XML etc. based this configuratin view has been prepared and the information from model i.e. POJO it will be put on the view and response will be send back to browser.

 Spring 3 MVC Request Flow:
1. Request lands to Front Controller i.e. DispatcherServlet
2. Capture the Request Locale i.e use for internationalization i.e Read .properties files
3. Check for multipart-file(MIME type header or not) upload data from distributed application
4. Consult with HandlerMapping for which Controller to be invoked
5. and Then responsibility is given to the Handler Chain
6. This Handler Chain is responsible to be invoked some of the interceptors that needs to be invoked before of a controller and after the controller that means interceptors are here like very to similar to the filters that help to separate the pre-process logic and post-process logic.
7. After process of pre-process interceptor return to the controller process the post-process logic.
8. Then return to the view resolver prepared the view based on your configuration decide the which configuration (JSP, Velocity, PDF etc.) to be invoked.
9. After choosing view technology prepare the view and return the response back to the client. 
Spring MVC Details
 Spring 3 MVC Framework- Initialization:
Spring MVC Init
MultipartResolver: Interface to handle the file uploads
LocaleResolver: Helps to resolve the locale from the request
ThemeResolver: Resolve a theme for a request(CSS)
HandlerMapping: Maps the Request to Handlers (Controllers)
HandlerAdapter: Plugs the other frameworks handlers
HandlerExceptionResolver: Mapping of the exceptions to handlers and views
ViewResolver: Maps the view names to view instances

All the above mentioned components ie. HandlerMapping, Controller and ViewResolver are parts of WebApplicationContext which is an extension of the plain ApplicationContext with some extra features necessary for web applications.

Required Spring 3.0 MVC Configuration:

You need to map requests that you want the DispatcherServlet to handle, by using a URL mapping in the web.xml file. The following is an example to show declaration and mapping for spring3 DispatcherServlet example:
Step 1:- Configure the web.xml with DispatcherServlet and details of the application context file location.
<web-app id="WebApp_ID" version="2.4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xsi:schemalocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 
    <display-name>Spring MVC Application</display-name>

   <servlet>
      <servlet-name>spring3</servlet-name>
      <servlet-class>
         org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>

   <servlet-mapping>
      <servlet-name>spring3</servlet-name>
      <url-pattern>*.*</url-pattern>
   </servlet-mapping>

</web-app>
Step 2:- Configure the contextConfigLocation for the application context to be loaded.
<web-app id="WebApp_ID" version="2.4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xsi:schemalocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 
    <display-name>Spring MVC Application</display-name>

   <servlet>
      <servlet-name>spring3</servlet-name>
      <servlet-class>
         org.springframework.web.servlet.DispatcherServlet
      </servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>

   <servlet-mapping>
      <servlet-name>spring3</servlet-name>
      <url-pattern>*.*</url-pattern>
   </servlet-mapping>

   <context-param>
      <param-name>contextConfigLocation</param-name><param-value>/WEB-INF/spring3-servlet.xml</param-value></context-param>
   <listener>
      <listener-class>
         org.springframework.web.context.ContextLoaderListener
      </listener-class>
    </listener>
</web-app>
Step 3:- Configure the spring3-servlet.xml
<beans xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="
   http://www.springframework.org/schema/beans     
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">

   <context:component-scan base-package="com.dineshonjava">
   </context:component-scan>
   <context:annotation-config></context:annotation-config>
   <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix" value="/WEB-INF/jsp/"></property>
      <property name="suffix" value=".jsp"></property>
   </bean>

</beans>
Following are the important points about spring3-servlet.xml file:
  • The [servlet-name]-servlet.xml file will be used to create the beans defined, overriding the definitions of any beans defined with the same name in the global scope.
  • The <context:component-scan...> tag will be use to activate Spring MVC annotation scanning capability which allows to make use of annotations like @Controller and @RequestMapping etc.
  • The InternalResourceViewResolver will have rules defined to resolve the view names. As per the above defined rule, a logical view named hello is delegated to a view implementation located at /WEB-INF/jsp/hello.jsp .
@Controller:
  •  Used at the class level
  • Tells the spring framework that the marked class acts as a controller.
@Controller
public class EmployeeController{

}
@RequestMapping:
  • Can be used at the class level and method level in controllers.
  • Arguments:-
       -URL[]
       -HTTP Methods[]-GET, POST, DELETE, TRACE, OPTIONS, HEAD, PUTS. Defaults method supported is GET
       -params[]-used to check if a request parameter matches with a value and only if the conditions passes the method or controller processes the request.
    (eg. @RequestMapping params="myName=guest" )
    -headers[]-used to check if a request header matches with a value and only if the condition passes the method or controller processes the request
    (eg. @RequestMapping headers="myheader=guestHadder")
Next section will show you how to create your actual components ie. Controller, Model and View.

Defining a Controller

DispatcherServlet delegates the request to the controllers to execute the functionality specific to it. The @Controller annotation indicates that a particular class serves the role of a controller. The @RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.
@Controller
@RequestMapping("/employee/*")
public class EmployeeController{
 
   @RequestMapping("add", method = RequestMethod.POST)
   public String createEmployee(){}//appcontext/employee/add
   @RequestMapping("delete", method = RequestMethod.GET)
   public String deleteEmployee(){}//appcontext/employee/delete
   @RequestMapping("details")//By default the method is GET
   public String getEmployeeDetails(){}//- /appcontext/employee/details

}
You can write above controller in another form where you can add additional attributes in @RequestMapping as follows:
@Controller
public class EmployeeController{
 
   @RequestMapping("add", method = RequestMethod.POST,value=/employee)
   public String createEmployee(){}//appcontext/employee/add
   @RequestMapping("delete", method = RequestMethod.GET,value=/employee)
   public String deleteEmployee(){}//appcontext/employee/delete
   @RequestMapping("details",value=/employee)//By default the method is GET
   public String getEmployeeDetails(){}//- /appcontext/employee/details

}
The value attribute indicates the URL to which the handler method is mapped and the method attribute defines the service method to handle HTTP GET request. There are following important points to be noted about the controller defined above:
  • You will defined required business logic inside a service method. You can call another methods inside this method as per requirement.
  • Based on the business logic defined, you will create a model within this method. You can setter different model attributes and these attributes will be accessed by the view to present the final result. This example creates a model with its attribute "message".
  • A defined service method can return a String which contains the name of the view to be used to render the model.
Creating JSP Views

Spring MVC supports many types of views for different presentation technologies. These include - JSPs, HTML, PDF, Excel worksheets, XML, Velocity templates, XSLT, JSON, Atom and RSS feeds, JasperReports etc. But most commonly we use JSP templates written with JSTL. So let us write a simple employee view in /WEB-INF/emp/employee.jsp:
<html>
   <head>
   <title>Hello Spring MVC</title>
   </head>
   <body>
   <h2>
${name}</h2>
</body>
</html>
Here ${name} is the attribute which we have setup inside the Controller. You can have multiple attributes to be displayed inside your view.
Spring Web MVC Framework Examples:

Based on the above concepts, let us check few important examples which will help you in building your Spring Web Applications:
S.N.Example & Description
1Spring MVC Hello World Example
This example will explain how to write a simple Spring Web Hello World application.
2Spring MVC Form Handling Example
This example will explain how to write a Spring Web application using HTML forms to submit the data to the controller and display back a processed result.
3Spring Page Redirection Example
Learn how to use page redirection functionality in Spring MVC Framework.
4Spring Static Pages Example
Learn how to access static pages along with dynamic pages in Spring MVC Framework.
5Spring Exception Handling Example
Learn how to handle exceptions in Spring MVC Framework.
6Spring 3.0 MVC with Hibernate 3.0 CRUD Example
Learn how to configure Spring 3 MVC with Hibernate 3 in Spring MVC Framework.
7Spring 3 MVC Tiles Plugin with Example
Learn how to configure Spring 3 MVC with Tiles configuration with example.
8Spring 3 MVC Interceptor with example
Learn how to configure Spring 3 MVC with Interceptor configuration with example.
9Spring 3 MVC Internationalization & Localization with Example
In this part we will discuss about Internationalization (I18N) and Localization (L10N) in Spring 3.0 MVC.
10How to write RESTful Web Services using Spring 3.0 MVC
How to write RESTful Web Services using Spring 3.0 MVC
11Spring 3.0 MVC with MongoDB CRUD Example
This is the CRUD application using the NoSQL database with Spring 3.0 MVC.
12Spring CRUD Example using One to One Mapping of Two Tables
This is the CRUD application using the One to One Mapping in two tables of database with Spring 3.0 MVC.
13Spring CRUD Example using Many to One Mapping
This is the CRUD application using the Many to One Mapping in three tables of database with Spring 3.0 MVC.




17 comments:

  1. please give me validations using spring mvc

    ReplyDelete
    Replies
    1. Hi

      Please see the following example where we are using Spring Validation.

      http://www.dineshonjava.com/2013/08/spring-crud-example-using-many-to-one.html#.UhUEtT9jxH0

      Thanks,
      Dinesh

      Delete
  2. Thanks for Response

    I am new to Spring and Hibernate i can't Understand relationships please explain all Relationships

    Tahnks
    Ravi

    ReplyDelete
  3. Hai Dinesh i am so confusion with relationships please explain one by one with example

    your blog very useful to learning spring to me ...
    please explain all relationships with dynamic examples

    Thanks
    Ravi

    ReplyDelete
    Replies
    1. Hi Ravi,

      I will provide you some more examples on mapping as soon as possible.

      Thanks,
      Dinesh

      Delete
  4. Hai Anamika

    Thank you for response
    please send mapping examples with explanation(raviteja553@gmail.com) This is my mail id

    Thanks
    Ravi

    ReplyDelete
  5. Hi dinesh

    I strugluede with java.lang.NumberFormatException: For input string: ""

    please reslove this error.

    ReplyDelete
    Replies
    1. Hi Ravi,

      In which place and which file you are getting this problem.
      For resolving this check null and empty string before parsing it to Number.

      Thanks,
      Dinesh

      Delete
  6. Hi dinesh in one jsp i am having 2 foms but only one submit button for update or edit. and for the 2 forms 2 different tables are there in data base. So my requirement is wen I want to edit and update the data should be saved into 2 different tables in the database, can u explain using struts n hibernate n springs integration

    ReplyDelete
    Replies
    1. Hi, we can use only one submit of one form.
      Please provide more detail for your requirement at admin@dineshonjava.com.

      Thanks,
      Dinesh

      Delete
  7. Hi Dinesh,

    Can u please post Spring 3 integration Hibernate 3 on tomcat with database oracle.

    ReplyDelete
    Replies
    1. http://www.dineshonjava.com/2012/12/spring-mvc-with-hibernate-crud-example.html

      Delete
  8. Hi dinesh,

    Can u please help me in development of Single Page Application by using Angularjs+Spring+Restful

    ReplyDelete
    Replies
    1. Hi Pallavi,

      As soon as possible we provide Angularjs tutorial where we explain this application.
      Thanks for showing interesting in this site. Keep learning with us :)

      Thanks,
      Dinesh

      Delete
  9. Hi dinesh,
    What use of @modelAttribute in this program.could you explai clearly.
    Thank you.....

    ReplyDelete
    Replies
    1. An @ModelAttribute on a method argument indicates the argument should be retrieved from the model. If not present in the model, the argument should be instantiated first and then added to the model. Once present in the model, the argument's fields should be populated from all request parameters that have matching names. This is known as data binding in Spring MVC, a very useful mechanism that saves you from having to parse each form field individually.

      For example- its populate model data fetching from JSP or another view templates..
      public String saveEmployee(@ModelAttribute EmployeeBean bean) {
      empDao.save(bean);
      }

      or we can also use ModelAttribute as on method like below.. it populate model after fetching from database.

      @ModelAttribute
      public String getEmployee(int empId) {
      empDao.getEmployee(empId);
      }

      And another point about "command" value in model attribute. Its mean nothing but it fetching the name of model attribute from command attribute of JSTL's from tag.
      Example-
      <form:form name="empForm" commandName="emoployeeBean" action="saveEmployee/">

      Here if you not give commandName attribute in JSTL form tag then by default name as model name starting with small letter.

      Thanks,
      Dinesh

      Delete