Spring Web MVC Components
To prepare Spring Web MVC Applications we have to use the following Components.
- View
- web.xml
- DispatcherServlet
- HandlerMapping
- Controller Component
- Command Class
- View Resolver
- Spring Configuration File
From the above diagram,
- Submitting request from Client to Server-Side web application, where DispatcherServlet will receive request.
- DispatcherServlet will interact with HandlerMapping to get Controller name and location.
- HandlerMapping will return the name and location of the Controller class.
- DispatcherServlet will recognize the name and location of the Controller class and perform loading and instantiation of the Controller class.
- Depending on the Controller, Form data will be stored in Command Object and that Command object data will be used in Controller class.
- After executing Business logic, Controller class will return ModelAndView object, which contains logical name of the view in View object and Model object is a Map contains Model Objects in order to use that data in View part.
- DispatcherServlet will interact with ViewResolver in order to get the name and location of the View page.
- ViewResolver will return View object with the name and location of the View page.
- DispatcherServlet will interact with View part with Model part in order to prepare response.
- View part will prepare response and submitting that response to DispatcherServlet.
- DispatcherServlet will generate the required response to Client.
1. View
What is the requirement to use View part in Web applications?
- It will improve Look and Feel to the web applications.
- It will provide entry point for the users in order to interact with applications.
- It will provide very good environment to take data from users in order to submit data to the server-side application.
- It able to provide very good environment to perform Client-Side data validations by using Java Script functions.
- It allows to specify different types of requests like GET, POST, HEAD etc. to the web applications.
There are two types of View parts are existed.
1. Informational View
- It able to display messages to the users, status of the server-side actions.
- It will not include forms, it will not take data from Users, simply it will display data to the users.
2. Form Based View
It will include forms to take data from users and to submit that data to the Users.
To prepare View part, we will use View based Tech like AWT, SWING, JAVA FX, html, Jsp, velocity, freemarker etc.
Spring Framework is able to allow all the advanced view tech, but at basic level, We will use JSP tech with Spring provided tag library.
2. web.xml [Deployment Descriptor]
web.xml is deployment descriptor, it will provide metadata about the web application which is required by the container in order to identify the server-side components and in order to execute server-side components.
In web applications, web.xml file is responsible for
- welcome files configuration
- Context parameters configuration
- Servlets configuration
- Filters configuration
- Listeners configuration
- Session time out configuration
- Error Pages configuration
- Tag Libraries configuration
- Security conf etc.
In Spring web MVC applications, web.xml file requirement is to configure Font Controller that is DispatcherServlet in order to activate FrontController by Web containers. In Spring Framework, DispatcherServlet is FrontControiller provided by Spring Framework in the form of “org.springframework.web.servlet.DispatcherServlet”. In DispatcherServlet conf, we will provide the following configuration details:
a. DispatcherServlet class conf
- Logical name of the Dispatcher Servlet conf.
- DispatcherServlet class conf.
- Initialization Parameters conf.
- Load on Startup Configuration.
b. URL Mapping Def
Where DispatcherServlet must have logical name, on the basis of this logical name only we will prepare Spring configuration file name, that is logical_Name-servlet.xml
<servlet-name>dispatcherServlet</servlet-name>
Note
- In the above case, Spring configuration file name must be dispatcherServlet-Servlet.xml
- Where DispatcherServlet class must be configured with its fully qualified name in order to activate FrontController.
E.g.
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
- Where Initialization Parameters are required to create Framework related objects like Handlermapping, HandlerAdapter, ViewResolver etc.
- The default name and location of Spring configuration file is under WEB-INF folder with the name “Servlet_Logical_Name-servlet.xml”, but, if we want to change this name and location then we must use “contextConfigLocation” initialization parameter in DispatcherServlet configuration.
E.g
<init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/config/myconfig.xml</param-value> </init-param>
Where load-on-startup configuration is required in order to perform DispatcherServlet loading, instantiation and initialization at the time of server startup, where DispatcherServlet initialization is required to load the complete Spring web MVC framework.
E.g
<load-on-startup>1</load-on-startup>
Where URL pattern definition is required for each and every Servlet in web applications. In general, in web applications, we will define URL patterns for the Servlets in the following three approaches.
- Exact Match Method
- Directory Match Method
- Extension Match Method
From the above URL pattern definitions, DispatcherServlet required to use either Directory Match method [/*] or Extension Match Method[*.do] in order to trap all the requests from Clients to DispatcherServlet.
<web-app> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>*.do</url-pattern> or <url-pattern>/*</url-pattern> </servlet-mapping> </web-app>
3. DispatcherServlet
The main intention of the Front Controller in web applications is,
- Getting request from clients.
- Identifying the respective Model component or Business component which includes business logic.
- Executing Business Logic which is existed in Business component.
- Identifying the respective View part in order to generate response.
- Forwarding request to view part in order to generate dynamic response.
In Spring web MVC module, DispatcherServlet is acting as the Front Controller provided by Spring Framework in the form of “org.spring framework.web.servlet.DispatcherServlet”. Spring Framework has provided DispatcherServlet with the following Structure.
Where HttpServletBean is the first Spring-aware class in the hierarchy. It injects the bean‟s properties using the servlet init-param values received from the web.xml or from WebApplicationInitializer.
Where FrameworkServlet integrates the Servlet functionality with a web application context, implementing the ApplicationContextAware interface. But it is also able to create a web application context on its own.
Where DispatcherServlet will perform the following actions in Spring web MVC applications in order to process the requests.
From the above diagram,
1. When we start server, container will perform the following actions.
- Container will recognize all the web applications which are existed under webapps folder.
- Container will deploy all the web applications under server space.
- Container will create a separate ServletContext object for each and every web application which we deployed.
2. While deploying web application, container will perform the following actions.
- Container will recognize web.xml file under WEB-INF folder.
- Container will perform web.xml file loading, parsing and reading the content from web.xml file.
- While parsing web.xml file, Container will recognize load-on-startup configuration under DispatcherServlet configuration.
- With the load-on-startup configuration, Container will search for DispatcherServlet under classes folder, if it is not existed then container will search for DispatcherServlet under web application lib folder.
- When DispatcherServlet identifies then container will perform DispatcherServlet loading, instantiation and initialization at the time of server startup or at the time of web application deployment.
3. As part of DispatcherServlet initialization, DispatcherServlet will perform the following actions.
- DispatcherServlet will recognize WebApplicationContext implementation class and perform WebApplicationContext loading, instantiation and initialization.
- As part of WebApplicationContext initialization, WebApplicationContext will recognize Servlet configuration file under WEB-INF folder with the name [Servlet-Name] -servlet.xml and WebApplicationContext will perform Spring configuration file loading, parsing and reading the content into Configuration object.
- After getting all the configuration details from spring configuration file into Configuration object, WebApplicationContext container will create bean objects which we configured under spring configuration file.
- After getting all bean objects, WebApplicationContext will create Framework objects like HandlerMapping, HandlerAdapter, ViewResolver, ThemeResolver, LocaleResolver etc. as part of WebApplicationContext initialization.
4. When we submit request from client to Server then Protocol will take request and perform the following actions.
- Protocol will establish connection between client and server on the basis of the Server IP Address and Port number.
- Protocol will create request format contains Header part and Body part, where Header part is able to manage Clients metadata and Body part is able to manage Request parameters data which are provided by the user at client browser.
- Protocol will carry request format to Server, where Server will forward request to web container.
5. When request is coming to the container then Web Container will take URL pattern value from request format and container is trying to compare the URL pattern of the DispatcherServlet which we configured in web.xml file, where if the URL pattern is matched with DispatcherServlet URL pattern then container will forward request to DispatcherServlet.
6. When request is coming to the DispatcherServlet then DispatcherServlet will perform the following actions
- DispathcerServlet will keep all the Framework objects like HandlerMapping, HandlerAdapter, ViewResolver, ThemeResolver, LocaleResolver etc. in request scope in order to make available to the Handler and View part.
- DispatcherServlet will interact with HandlerMapping object to get Handler or Controller object by executing getHandler() method.
- When DispatcherServlet call getHandler() on HandlerMapping object , HandlerMapping will identify the respective Handler object and its configured interceptors then Handler Mapping will arrange all the interceptors before Handler and return HandlerExecutionChain object which contains Handler object and a set of interceptors. (Interceptors are like Filters in servlets, which are used to perform pre-processing and post-processing activities for any web resource.)
- After getting HandlerExecutionChain object, DispatcherServlet will use HandlerAdapter object to access Handler by using handle() method, where HandlerAdapter will execute all the interceptors in order to perform pre-processing activities by calling preHandle() method.
- After executing all the interceptors, HandlerAdpter will access business logic which is included in Handler or Controller component.
- By the execution of Business login in Handler class, Handler will return ModelAndView object to HandlerAdapter by executing all the interceptors in reverse in order to provide post-processing activities by executing postHandle() method, where HandlerAdapter will send the received ModelAndView object to DispatcherServlet.
Where ModelAndView object contains View object and Model object, where View object contains view name in order to identify view part and Model object contains no of Objects to provide data to the View part.
- After getting ModelAndView object, DispatcherServlet will interact with ViewResolver in order to identify view JSP page url on the basis of View name.
- When View is identified in web application then DispatcherServlet will execute the corresponding view page by getting data from Model part a and DispatcherServlet will prepare Response for the client.
- When DispatcherServlet prepares response, DispatcherServlet will send response to client, where Protocol will take that response and protocol will perform the following actions.
Protocol will prepare response format contains Header part and Body part, where Header part is able to manage response headers data like response size, type of response etc. and Body part is able to manage the actual dynamic response.
Protocol will carry response format to client, where client browser will display the generated response.
When response is generated at client browser, protocol will destroy the connection which is established between client and Server.
When we shut down the server or when we undeployed the web application then container will perform DispatcherServlet deinstantiation, with this, all the Spring Framework objects like HandlerMapping, HandlerAdapter, viewResolver etc. are destroyed.
4. HandlerMapping
The main intention of HandlerMapping is to map incoming request to the Handler class that can handle requests. When request is coming to DispathcerServlet, DispatcherServlet will forward request to HandlerMapping , where HandlerMapping will identify the respective Handler class and its associated interceptors then HandlerMapping will create HandlerExecutionChain with Handler class object and interceptors stack and return HandlerExecutinChain to DispatcherServlet.
Spring Framework has provided the following HandlerMappings in order to map requests to Handler classes.
- BeanNameUrlHandlerMapping
- SimpleUrlHandlerMapping
- ControllerClassNameHandlerMapping
- CommonsPathMapHandlerMapping
In Spring web MVC applications, if we want to use the HandlerMapping classes then we must configure them in Spring configuration File.
1. BeanNameUrlHandlerMapping
It is default HandlerMapping in Spring applications, it will be used by Spring framework when no HandlerMapping is configured in Spring configuration file. This HandlerMapping map URLs to beans with names that start with a slash (“/”), similar to how Struts maps URLs to action names. Spring Framework has provided this Handler mapping like
org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping
<beans> ----- <bean name=”/welcome.htm” class=”com.ashok.spring.controller.WelcomeController”/> <bean name=”/hello.htm” class=”com.ashok.spring.controller.HelloController”/> <bean name=”handlerMapping” class=”org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping”/> ------ </beans>
In the above configuration, if we submit request with the url http://localhost:8080/app/welcome.htm then BeanUrlHandlermapping will forward request to WelcomeController .
In the above configuration, if we submit request with the url http://localhost:8080/app/hello.htm then BeanUrlHandlermapping will forward request to HelloController.
2. SimpleUrlHandlerMapping
This HandlerMapping is able to map Handler or Controller classes by matching URL path with the property key of the properties. Spring Framework has provided this HandlerMapping like
org.springframework.web.servlet.handler.SimpleUrlHandlermapping
<beans> ........ <bean name=”addEmp” class=”com.ashok.spring.controller.AddEmployeeController”/> <bean name=”searchEmp” class=”com.ashok.spring.controller.SearchEmployeeController”/> <bean name=”deleteEmp” class=”com. ashok.spring.controller.DeleteEmployeeController”/> <bean name=”handlerMapping” class=“org.springframework.web.servlet.handler.SimpleUrlHandlermapping”> <property name=”mappings”> <props> <prop key=”addEmployee.htm”>addEmp</prop> <prop key=”searchEmployee.htm”>searchEmp</prop> <prop key=”deleteEmployee.htm”>deleteEmp</prop> </props> </property> </bean> </beans>
If we submit request like http://localhost:8080/app/addEmployee.htm then SimpleUrl-HandlerMapping will forward request to AddEmployeeController class
If we submit request like http://localhost:8080/app/searchEmployee.htm then SimpleUrl-HandlerMapping will forward request to SearchEmployeeController class
If we submit request like http://localhost:8080/app/deleteEmployee.htm then SimpleUrl-HandlerMapping will forward request to DeleteEmployeeController class
3. ControllerClassNameHandlerMapping
This HandlerMapping follows a simple convention for generating URL path mappings from the class names of registered Controller beans as well as @Controller annotated beans.
For simple Controller implementations (those that handle a single request type), the convention is to take the short name of the Class, remove the ‘Controller’ suffix if it exists and return the remaining text, lower-cased, as the mapping, with a leading /. Spring Framework has provided this HandlerMapping like
org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping
<beans> <bean id=”welcome” class=”com.ashok.spring.controller.WelcomeController”/> <bean name=”hello” class=”com. ashok.spring.controller.HelloController”/> <bean name=”handlerMapping” class=“org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping”/> </beans>
If we submit request like http://localhost:8080/app/welcome* then ControllerClassName-HandlerMapping will access WelcomeController class
If we submit request like http://localhost:8080/app/hello* then ControllerClassName-HandlerMapping will access HelloController class
4. CommonsPathMapHandlerMapping
Following is the one of the implementation of HandlerMapping interface
org.springframework.web.servlet.handler.CommonsPathMapHandlerMapping
Following is the designed to recognize Commons attributes meta data attributes of type PathMap defined in the application controller and automatically wires them in to the current DiapatcherServlet’s Web-application context.
org.springframework.web.servlet.handler.CommonsPathMapHandlerMapping
To use this HandlerMapping the controller class must have a class level metadata of the form
@org.springframework.web.servlet.handler.commonsattribures.PathMap("/mypath.spring")
We can configure multiple path maps for a single controller.
@org.springframework.web.servlet.handler.commonsattribures.PathMap("/mypath.spring") public class FirstController implements Controller { public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { System.out.println("we are in handleRequest()"); ModelAndView mav=null; return mav; } }
5. Controller Component
The main intention of Controller in Spring web MVC is to manage application logic or to have controller logic to manage Service layer provided business methods access. To prepare Controller classes in Spring web MVC applications Spring framework has provided the following predefined Library
All the above Controller classes are the implementation of org.springframework.web. servlet.mvc.Controller interface. org.springframework.web.servlet.mvc.Controller interface has provided the following method to include business logic or controller component logic.
public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception
In Spring web MVC application we can prepare Controller class either by implementing Controller interface or by extending the above Controller classes.
Where ModelAndView is an object that holds both the model and view. The handler returns the ModelAndView object and DispatcherServlet resolves the view using View Resolvers and View. The View is an object which contains view name in the form of the String and model is a map to add multiple objects. To create ModelAndView object we have to use the following constructors.
public ModelAndView() public ModelAndView(String view_Name) public ModelAndView(String view_Name, Map model) public ModelAndView(String view_Name, HttpStatus status) public ModelAndView(String view_Name, String model_Name, Object model)
Note
If we want to use Controller classes in Spring web MVC applications then we have to configure in Spring configuration File.
6. Command Class
The main intention of Command class is to store form data which is submitted by the client when we use FormCommandControllers. It is like ActionForm component in Struts framework.
public class User{ private String uname; private String upwd; setXXX() and getXXX() }
7. View Resolver
In Spring MVC, view resolvers enable you to render models in a browser without tying you to a specific view technology like JSP, Velocity, XML etc. There are two interfaces that are important to the way Spring handles views are ViewResolver and View. The ViewResolver provides a mapping between view names and actual views. The View interface addresses the preparation of the request and hands the request over to one of the view technologies.
Spring Framework has provided the following ViewResolvers
1. ViewResolver – View Resolvers get a org.springframework.web.servlet.View based on a view name.
2. ContentNegotiatingViewResolver – This is an implementation of a view resolver based on the request file name or Accept header. This class delegates view resolution to other view resolvers that are configured. The class uses the MediaType from the request to determine a view. The class first determines the MediaType, then asks each ViewResolver to return a view. The class then compares the all returned views‟ content type and the one that is most compatible with the request MediaType is chosen.
3. BeanNameViewResolver – This resolver implemenatation resolves a view name as a bean name registered in the application context. In other words, the view is registered as a bean and this resolver gets the name of that bean
4. UrlBasedViewResolver – This directly resolves a view name to a URL without any explicit mapping. The view names can be the URL themselves or a prefix or suffix can be added to get the URL from the view name. To redirect a URL use the “redirect:” prefix. To forward a URL use the “forward:” prefix.
5. InternalResourceViewResolver – This is a subclass of UrlBasedViewResolver and supports an InternalResourceView. An InternalResourceView is a wrapper for JSP or some other resource that reside in the same web application. It exposes the model objects as request attributes. If JSTL API is present then the resolver resolves the view name to a JSTLView. An InternalResourceViewResolver needs to be last, if a chain of view resolvers is used, since this resolves the view name irrespective of whether the actual resource is present or not.
6. FreeMarkerViewResolver – This is a subclass of UrlBasedViewResolver that supports FreeMarkerView and its subclasses. The View Class generated can be specified by the „viewClass‟ property. VelocityViewResolver-This is a subclass of UrlBasedViewResolver that supports VelocityView and its subclasses.
7. JasperReportsViewResolver – Supports AbstractJasperReportsView by resolving the view name to the URL of the report file.
8. XsltViewResolver – Supports XsltView by resolving the view name to the URL of the XSLT Stylesheet.
In spring Web MVC applications we have to configure view Resolver in Spring configuration file with the name “viewResolver” id name.
E.g
<bean id=”viewResolver” class=”org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name=”prefix” value=”WEB-INF”/> <property name=”suffix” value=”.jsp”/> </bean>
8. Spring Configuration File
In Spring web MVC application, Spring configuration file is recognized by WebApplicationContext container with the name [DS_Logical_Name] -servlet.xml under WEB-INF folder. The main intention of Spring configuration file in Spring Web MVC application is to provide the configuration details like,
- Controller classes and their dependencies configuration
- HandlerMapping configuration.
- ViewResolver Configuration
<beans> <bean name=”/welcome.htm” class=”com.ashok.spring.controller.WelcomeController”/> <bean name=”/hello.htm” class=”com.ashok.spring.controller.HelloController”/> <bean name=”handlerMapping” class=”org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping”/> <bean id=”viewResolver” class=”org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name=”prefix” value=”WEB-INF”/> <property name=”suffix” value=”.jsp”/> </bean> </beans>