Spring MVC
Spring MVC (Model view controller) is based on the MVC design pattern, it is a software architecture design pattern. It provides solution to layer an application by separating three concerns business, presentation and control flow.
Spring 5 Design Pattern Book
- 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.
Popular Tutorials
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 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.
In Spring 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 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 Framework- Initialization
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 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 |
---|---|
1 | Spring MVC Hello World Example This example will explain how to write a simple Spring Web Hello World application. |
2 | Spring 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. |
3 | Spring Page Redirection Example Learn how to use page redirection functionality in Spring MVC Framework. |
4 | Spring Static Pages Example Learn how to access static pages along with dynamic pages in Spring MVC Framework. |
5 | Spring Exception Handling Example Learn how to handle exceptions in Spring MVC Framework. |
6 | Spring 3.0 MVC with Hibernate 3.0 CRUD Example Learn how to configure Spring 3 MVC with Hibernate 3 in Spring MVC Framework. |
7 | Spring 3 MVC Tiles Plugin with Example Learn how to configure Spring 3 MVC with Tiles configuration with example. |
8 | Spring 3 MVC Interceptor with example Learn how to configure Spring 3 MVC with Interceptor configuration with example. |
9 | Spring 3 MVC Internationalization & Localization with Example In this part we will discuss about Internationalization (I18N) and Localization (L10N) in Spring 3.0 MVC. |
10 | How to write RESTful Web Services using Spring 3.0 MVC How to write RESTful Web Services using Spring 3.0 MVC |
11 | Spring 3.0 MVC with MongoDB CRUD Example This is the CRUD application using the NoSQL database with Spring 3.0 MVC. |
12 | Spring 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. |
13 | Spring 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. |
- Spring MVC Web Tutorial
- Spring MVC Interview Questions
- MVC Design Pattern
- Spring MVC DispatcherServlet
- Spring MVC WebApplicationContext and Root Application Context
- Spring MVC @Controller Annotation
- Spring MVC @RequestMapping Annotation
- Spring MVC @RequestParam Annotation
- Spring MVC ContextLoaderListener
- Spring MVC @RequestParam and @PathVariable annotations
- Spring MVC Hello World Example
- Spring MVC Exception Handling Example
- Spring MVC with Hibernate CRUD Example
- Spring MVC Tiles Plugin with Example
- Spring MVC Interceptor with example
- Spring MVC with MongoDB CRUD Example
- Spring MVC Internationalization & Localization with Example
please give me validations using spring mvc
Hi
Please see the following example where we are using Spring Validation.
https://www.dineshonjava.com/2013/08/spring-crud-example-using-many-to-one.html#.UhUEtT9jxH0
Thanks,
Dinesh
Thanks for Response
I am new to Spring and Hibernate i can't Understand relationships please explain all Relationships
Tahnks
Ravi
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
Hi Ravi,
I will provide you some more examples on mapping as soon as possible.
Thanks,
Dinesh
Hai Anamika
Thank you for response
please send mapping examples with explanation(raviteja553@gmail.com) This is my mail id
Thanks
Ravi
Hi dinesh
I strugluede with java.lang.NumberFormatException: For input string: ""
please reslove this error.
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
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
Hi, we can use only one submit of one form.
Please provide more detail for your requirement at admin@dineshonjava.com.
Thanks,
Dinesh
hi dinesh am spring developer
Hi Dinesh,
Can u please post Spring 3 integration Hibernate 3 on tomcat with database oracle.
https://www.dineshonjava.com/2012/12/spring-mvc-with-hibernate-crud-example.html
Hi dinesh,
Can u please help me in development of Single Page Application by using Angularjs+Spring+Restful
Hi dinesh,
What use of @modelAttribute in this program.could you explai clearly.
Thank you…..
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
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
Hi Dinesh,
Your contents are good. Though you have many grammatical errors which makes it less understandable. Please do consider someone to proof read before posting new topics. It will surely help the readers to understand and comprehend better.
Hi!
How to upload my war file on my domain via tomcat vps server. Please help . If be possible mail me the process. link2virendra@gmail.com