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.
Popular Tutorials
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-
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.
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.
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.
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:
@Controller:
@Controller public class EmployeeController{ }
@RequestMapping:
Next section will show you how to create your actual components ie. Controller, Model and View.
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:
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>
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. |
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…