This Spring web MVC tutorial gives an overview of Spring web MVC and what all components are there in the Spring MVC framework.
Spring MVC
Spring web MVC as the name suggests follows the MVC (Model-View-Controller) architecture. Spring web MVC, just like every other thing in Spring framework, is configurable and loosely coupled.
Just to give a heads up here is a brief description what MVC stands for-
- Model- Model in the MVC encapsulates the application data that is generally send from one layer to another (Web layer to service layer, Service layer to web layer). Model is generally a POJO (Java bean with getters and setters).
- View- View is the user interface that renders the Model data.
- Controller- Controller is the component that processes the request. This processing generally results in some data that is passed to the View component in the form of Model.
Components in Spring Web MVC framework
In a MVC application, a request (clicking a link, submitting a form) passes through several components as the incremental processing happens. In Spring MVC also there are different components.
DispatcherServlet in Spring MVC
DispatcherServlet is Spring MVC’s front controller servlet.
Front controller is a web application design pattern where a single servlet handles all the requests and responses. Every request comes to that single servlet which identifies the component that can further process the request and delegates the responsibility to that component.
Configuring DispatcherServlet
You can configure DispatcherServlet in your Spring MVC application using XML configuration or using Spring Java configuration.
If you are using XML configuration then DispatcherServlet will be defined in the web.xml.
<servlet> <servlet-name>mvcexample</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvcexample</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
Here <servlet-name> is important because DispatcherServlet tries to load the Spring application context from the XML file whose name is <servlet-name>-servlet.xml. For example here name is mvcexample so DispatcherServlet will look for the xml named mvcexample-servlet.xml in WEB-INF directory.
<servlet-mapping> tag defines the URL pattern to indicate the URLs served by the DispatcherServlet.
Refer Spring Web MVC Example With Annotations to see the complete Spring MVC example with XML configuration.
If you are using Java configuration then DispatcherServlet will be defined using the Java class as follows.
public class SpringMVCWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[] {RootConfig.class}; } @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] {WebConfig.class}; } @Override protected String[] getServletMappings() { return new String[] {"/"}; } }
Spring framework detects the class extending AbstractAnnotationConfigDispatcherServletInitializer, that class is automatically used to configure DispatcherServlet. Class defined in getServletConfigClasses() method is used to load Spring application context. If there is any other application context that is loaded using the class defined in the method getRootConfigClasses().
Refer Spring Web MVC Java Configuration Example to see the complete Spring MVC example using Java config.
Controller in Spring Web MVC
DispatcherServlet delegates the request to Spring MVC Controller for further processing. There are generally many controllers with in an application, so DispatcherServlet uses HandlerMapping to map the request to the right controller.
The two main HandlerMapping implementations are-
- RequestMappingHandlerMapping- Which maps request to Controller and its methods that are having @RequestMapping annotation. Appropriate controller and controller method is chosen using the URL pattern provided along with the @RequestMapping annotation.
- SimpleUrlHandlerMapping- In this implementation of HandlerMapping collection is configured in the Spring application context that maintains explicit registrations of URI path patterns to controllers.
@Controller @RequestMapping(value = "/") public class MessageController { @RequestMapping(value = "/showUser", method = RequestMethod.POST) public String showUser(@ModelAttribute("user") User user, Model model) { model.addAttribute("firstName", user.getFirstName()); model.addAttribute("lastName", user.getLastName()); return "user"; } }
Here value attribute has the relative URL path for mapping the request to showUser() controller method.
method = RequestMethod.POST means this controller method handles HTTP post requests.
Model in Spring MVC
If you have noticed in the above Controller method Model is passed as a parameter. Model stores data in the form of (key, value) pair and addAttribute() method is used to store these (key, value) pairs. This Model is passed on to the view for rendering.
View in Spring MVC
Again if you notice the controller method it returns a String. That is the logical view name used to resolve the view.
Spring MVC defines the ViewResolver and View interfaces.
ViewResolver provides a mapping between view names (as returned by controller method) and actual views. That way you are not tied to a specific view technology.
View addresses the preparation of data before handing over to a specific view technology.
There are many ViewResolver implementations provided by Spring framework like XmlViewResolver, ResourceBundleViewResolver, UrlBasedViewResolver, InternalResourceViewResolver, FreeMarkerViewResolver.
The appropriate ViewResolver is defined in the application context XML, if XML configuration is used. Here is an example of InternalResourceViewResolver.
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean>
Or in a Java class in case of Java config.
@Configuration @EnableWebMvc public class WebConfig { @Bean public ViewResolver viewResolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/WEB-INF/jsp/"); resolver.setSuffix(".jsp"); return resolver; } ... ... }
Using the arguments passed on as suffix and prefix view name is created. For example if view name returned from controller is “home” then the JSP that has to be used as view will be found at the location- /WEB-INF/jsp/home.jsp.
How does Spring detect MVC related annotations
If you are using XML configuration then you can enable annotation-driven Spring MVC by using <mvc:annotation-driven> element.
In case of Java config @EnableWebMvc annotation is used to enable annotation-driven Spring MVC.
Spring Web MVC flow
Now when you have knowledge of all the Spring MVC component let’s see the whole Spring web MVC flow.
- Request is first handled by the
DispatcherServlet
. - Using the HandlerMapping, DispatcherServlet determines which controller is configured to process that specific request. This "request to controller mapping" is done using the URL pattern.
- In an application you will generally have Service and DAO Classes that will have most of the processing logic. From the controller class generally service class is called which in turn calls the DAO class.
- When controller is done with the processing there usually have some result data which forms the Model. Controller also sends the logical view name to resolve the view that will render the Model data.
- For resolving the view,
ViewResolver
class is used which is configured in the application context file. - Once the view is resolved, Model data is used to render the view.
That's all for this topic Spring Web MVC Tutorial. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Spring Tutorial Page
Related Topics
You may also like-
It’s a shame you don’t have a donate button! I’d certainly donate to this brilliant blog! I suppose for now I’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to fresh updates and will talk about this blog with my Facebook group. Chat soon!
ReplyDelete