Spring MVC Brief: Starting with the common concerns of the MVC framework

Source: Internet
Author: User

Any complete MVC framework needs to solve some common problems in the Web development process, such as request collection and distribution, data transfer and conversion, and the current most popular SPRINGMVC and Struts2 are no exception. In this paper, we first summarize the layered idea of MVC pattern and the problem of the MVC framework, and take this as an opportunity to combine the SPRINGMVC's entry-level case to introduce its processing to these problems from the point of view of principle and architecture, including the core issues of request processing flow, message transformation mechanism and data binding mechanism. Finally, this paper SPRINGMVC the two most popular MVC frameworks and
  
I. MVC pattern and framework
  
1. MVC mode
  
The architecture of Java WEB applications has gone through the Model1 and Model2 two times. In Model1 mode, the entire WEB application is composed of almost all JSP pages, with only a small amount of JavaBean to handle database connection, access and other operations. From an engineering point of view, JSP not only acts as a performance layer, but also acts as a controller, mixing control logic and performance logic, resulting in very low code reuse rates, which makes the application extremely difficult to extend and maintain.
  
Model2 is already a design pattern based on the MVC architecture. In Model2, the Servlet acts as a controller, responsible for receiving requests sent by the client, invoking the backend's JavaBean (business logic component) to process the business logic and forwarding the display logic to the corresponding JSP page based on the processing results. In Model2 mode, the model is played by JavaBean, the view is played by the JSP page, and the controller is played by the Servlet. The MODEL2 process is as follows:
  
Write a picture description here
  
More specifically, in Model2 (Standard MVC), the roles are divided as follows:
  
Model: By JavaBean, all the business logic and database access are implemented in model;
  
View: by JSP, responsible for collecting the user request parameters and the application processing results, status data presented to the user;
  
Controller: Performed by the Servlet, acting like a dispatcher, where all user requests are sent to the Servlet,servlet call Model to process the user request and invoke the JSP to render the result based on the processing result , or the servlet invokes the JSP directly to expose the application processing results to the user.
  
2. The MVC framework
  
The MVC pattern mentioned above is only a layered architectural idea and does not contain any concrete implementations. In Model2, we use JavaBean, JSP, and servlet respectively as model, view, and controller, which can be seen as the most basic implementation of the MVC pattern. But in fact, developers using MODEL2 to develop Java Web applications, in addition to focus on the development of business logic, but also need to consider a variety of issues, such as the flow and transformation between the front and back data, data validation problems, message conversion problems, etc. And there is no complete decoupling between the layers. Model2 these problems in fact are some common problems, in other words, Model2 abstraction and encapsulation degree is not enough, developers in the use of MODEL2 development, inevitably will be repeatedly built wheels, which greatly reduces the maintainability and reusability of the program.
  
In order to solve this problem, liberate the programmer's hands, some MVC framework has emerged. Struts is the world's first MVC framework, in particular, its Struts2 with WebWork has many excellent designs, and absorbs the essence of both the traditional struts and webwork, once the king of the MVC framework. However, compared with SPRINGMVC, Struts2 is so cumbersome and difficult to use. At the same time, with the wide application of spring and the relentless pursuit of lightweight frameworks by developers, SPRINGMVC is becoming a new king in the MVC framework.
  
Letting developers focus only on the processing of business logic is the ultimate goal of the MVC framework. Whether it is the former Struts2 or today's SPRINGMVC, their differences are more in the design of the pros and cons and delicate, but as an MVC framework, they will encapsulate and provide some basic components and functions to liberate the programmer's hands, such as:
  
The front-end controller that distributes the request (Dispatcherservlet in Strutsprepareandexecutefilter and Springmvc in Struts2);
  
The business controller that handles the request (action in STRUTS2 and Controller in SPRINGMVC);
  
Match the request URI to the request processing method (Handlermapping in Actionmapper and Springmvc in Struts2);
  
Invocation of the Request processing method (Handleradapter in Actionproxy and Springmvc in Struts2);
  
Type conversion problem--the flow of front and rear data;
  
Data verification;
  
abnormal configuration;
  
Internationalization and tag library;
  
File upload/download;
  
In fact, any complete MVC framework will abstract and encapsulate the above features. Compared with MODEL2, the MVC framework extracts and accomplishes a number of common steps that need to be repeated in real-world development, leaving developers with only the parts that are relevant to a particular application, greatly simplifying program development, enhancing program maintainability, and enhancing code reusability.
  
Two. Spring MVC core components and execution process
  
Spring MVC is a full-featured MVC module for building Web applications provided by the spring framework, and a lightweight web framework that implements the request-driven type of the Web MVC design pattern based on Java, well implemented the idea of the MVC architecture pattern and decoupled the Web layer's responsibilities. Generally, in an MVC framework, a controller is used to execute business logic and produce model data, whereas a view is used to render model data, although SPRINGMVC is no exception, as shown in:
  
Write a picture description here
  
1. SPRINGMVC Execution Process
  
The process of request processing in SPRINGMVC is briefly described, but in practice it does not depict the full picture of the SPRINGMVC framework processing an HTTP request. The request processing process of SPRINGMVC is described in detail, and the interactive process between the core components of SPRINGMVC is given.
  
Write a picture description here
  
1, the user sends the request to the server, requests by the spring MVC front-end controller Dispatcherservlet intercepts;
  
2, dispatcherservlet the request URL (Uniform Resource Locator) to parse, get the URI (Request resource Identifier). Then, based on the URI, call handlermapping to get all related objects for the handler configuration, including handler objects and interceptors for handler objects, which are encapsulated into a Handlerexecutionchain object return;
  
3, Dispatcherservlet According to obtain the handler, chooses a suitable handleradapter. A handleradapter will be used to process multiple (class) Handler and invoke Handler to actually process the request;
  
4. Before calling handler to actually process the request, Handleradapter will first convert the request message in combination with the user configuration (for example, to convert the Json/xml request message into a Java object). The model data in the request is then bound to the parameters of the processing method of the handler (Controller) through DataBinder. In the process of message transformation and data binding, Spring MVC will do some additional processing, such as data type conversion, data format work and data legitimacy check etc.
  
5, Handler calls the business logic component to complete the processing of the request, return a Modelandview object to Dispatcherservlet, the Modelandview object should contain the view name or view name and model;
  
6, Dispatcherservlet According to the returned Modelandview object, select a suitable viewresolver (view parser) to return to Dispatcherservlet;
  
7, Dispatcherservlet Call the view parser Viewresolver combined with model to render the views view;
  
8. Dispatcherservlet returns the view render result to the client.
  
In the eight steps above, core components such as Dispatcherservlet, Handlermapping, Handleradapter, and viewresolver work together to complete the spring MVC request-response workflow. The work done by these core components is transparent to the developer, that is, the developer does not need to be concerned about how these components work, and developers only need to focus on the business logic of the request in handler, which is the value of the MVC framework.
  
2. SPRINGMVC message Converter mechanism: Httpmessageconveter
  
In fact, when we make requests to the server, we can use a variety of data interchange formats, such as lightweight JSON and heavyweight XML, and, of course, other custom data interchange formats. But no matter what data Interchange format is used in the request sender, we can only read the original string message from the request stream, and we can only write the original string in the response stream. However, in the Java world, when we call the model component to process business logic, it is often a business-meaningful object to handle the dimension, so there is a message conversion problem when the request message arrives SPRINGMVC and the response message goes out from SPRINGMVC, that is, the request message ( String) to the translation of the Java object.
  
Zhang Xiaolong in the nature of the talk, said: "Just a platform, the flow of news in it." When we analyze SPRINGMVC's message converter mechanism, we can also get a similar sense. In the eyes of Springmvc's designer, a request message and a response message are abstracted as a request messages httpinputmessage and a response messages httpoutputmessage, respectively. When a request is processed, the request message is converted by the appropriate message converter into a parameter object in the request processing method and bound to the formal parameter of the request processing method through the DataBinder component, where the original request message may have many different forms, such as JSON and XML. Similarly, when a controller responds to a request, the return value of the request processing method can be not an HTML page, but a data in some other format, such as JSON and XML.
  
We know that Struts2 's own support for data interchange formats such as JSON and XML is not particularly good, and often requires some plug-ins (for example, Struts2 to compensate for the lack of native JSON support, Struts2-json-plugin plugin) to complete , and in Springmvc, the httpmessageconverter mechanism is used. Specifically, Httpmessageconveter is responsible for translating the request information into an object and using the DataBinder component to bind the object to the parameters of the request method or to output the response information. In particular, SPRINGMVC provides different httpmessageconverter implementation classes for commonly used message forms to handle them, and we can easily extend our custom message converters. However, as long as the "valid information" contained in these messages is consistent, various message converters will produce the same results. The differences between the various message parsing details are masked in different httpmessageconverter implementation classes.
  
As mentioned below, in SPRINGMVC you can use the @requestbody and @responsebody two annotations to complete the conversion of the request message to the object and the object to the response message, respectively. The underlying flexible message-transfer mechanism is supported by Httpmessageconverter.
  
3. SPRINGMVC Data Binding component: DataBinder
  
In fact, the SPRINGMVC message Converter mechanism Httpmessageconveter mentioned in the previous section is implemented on the basis of the SPRINGMVC data binding component DataBinder. Before Handleradapter invokes the specific method in handler to process the request, Handleradapter will convert the information in the request message in a way that is bound to the parameters of the request method in order to request processing, depending on the signature of the request method. In other words, SPRINGMVC will do a lot of other work during the time the request message arrives to actually call the processing method, including the conversion of request information, data conversion, data formatting, data validation and so on. In fact, the SPRINGMVC will parse the signature of the target processing method through the reflection mechanism and bind the request message to the parameters of the processing method. The core component of data binding is DataBinder, which has the following mechanism:
  
Write a picture description here
  
The Spring MVC framework passes a Parameter object instance of the ServletRequest object and its processing method to the Databinder,databinder call assembly in the spring Web The Conversionservice component in context makes data type conversion, data formatting work, and fills the message in ServletRequest into the Parameter object. The validator component is then called to validate the data legitimacy of the parameter object that already has the request message data bound, and eventually produces the data-bound result Bindingresult object. Where the Bindingresult object contains not only the parameter object of the completed data binding, but also the corresponding checksum error object, Spring MVC extracts the parameter objects from the Bindingresult object and verifies the error objects, and assigns them to the corresponding parameters of the processing method.
  
4. Summary
  
SPRINGMVC's request processing process can be summarized as follows: When SPRINGMVC receives the request, The front-end controller Dispatcherservlet calls handlermapping based on the request URI to distribute the request to Handlerexecutionchain objects with a series of interceptors and business controller controllers. The request then passes through each interceptor of the execution chain in turn, and eventually arrives at the business controller manager. The Handleradapter will further transform and parse the request message and bind it to the specific request handling method of the business controller controllers before the business controller controllers handle the request. The method then invokes a series of business logic components to process the request according to the request parameters, and passes the results of the processing containing the model data and the concrete view to the view resolver viewresolver for rendering, and finally dispatcherservlet the view render results back to the client.
  
From this process, we can visually see that SPRINGMVC solves the main concerns of a series of MVC frameworks, such as the collection, distribution and processing of requests, the flow, transformation, and binding of data between the front and back tables. In fact, Springmvc as a complete MVC framework also solves the basic problems of exception handling, internationalization, and tag library.
  
Three. SPRINGMVC Application development process profiling: XML configuration and annotation configuration
  
Once we are familiar with the SPRINGMVC request processing process, this section provides an introductory case for an in-depth understanding of the SPRINGMVC request processing process, as well as familiarity with the SPRINGMVC application development process. To develop a SPRINGMVC application, you first need to add spring support for our web project, and then we can build on the application based on the XML configuration or annotation configuration. This section shows the SPRINGMVC apps that are based on the XML configuration and annotation configuration, respectively.
  
1. SPRINGMVC Application development Process Demo:xml configuration
  
(1). Configure the front-end controller in Web. Dispatcherservlet
  
<?xml version= "1.0" encoding= "UTF-8"?>
  
<web-app xmlns:xsi= "http://www.w3.org http://www.acnet.cn//2001/XMLSchema-instance"
  
Xmlns= "Http://java.sun.com/xml/ns/javaee"
  
xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  
Id= "webapp_id" version= "2.5" >
  
<display-name>SpringMVCDemo</display-name>
  
<!--Configure Spring MVC's front-end controller: Dispatchcerservlet http://gouyily.cn/-
  
<servlet>
  
<servlet-name>springmvc</servlet-name>
  
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  
<!--SPRINGMVC configuration file path and name-
  
<init-param>
  
<param-name>contextconfiglocation   
<param-value>classpath:springmvc.xml</param-value>
  
</init-param>
  
<!--the web app loads as soon as it starts
  
<load-on-startup>1</load-on-startup>
  
</servlet>
  
<servlet-mapping>
  
<servlet-name>springmvc</servlet-name>
  
<url-pattern>/</url-pattern> <!--intercept all requests--
  
</servlet-mapping>
  
</web-app>
  
To apply the SPRINGMVC framework to a Web project, we first need to add a servlet--dispatchcerservlet to XML. Dispatcherservlet is the central point of access for SPRINGMVC, and its core function is to distribute requests and seamlessly integrate with the spring IOC container to get all the benefits of spring.
  
When configuring Dispatchcerservlet, we can specify the path to the SPRINGMVC configuration file to Dispatchcerservlet find and create a Webapplicationcontext container object based on the file configuration information. That is, the context environment. It is particularly important to note that Webapplicationcontext inherits from the ApplicationContext container, which is initialized in a way that differs from Beanfactory, ApplicationContext, Because Webapplicationcontext needs to be in a Web container environment to complete the task of starting the Spring Web application context. After initializing the Webapplicationcontext container, it is natural for developers to use Spring's IOC, AOP and other features.
  
Dispatcherservlet as a central access point for Spring Web MVC, you need to create an instance and initialize the Webapplicationcontext container as soon as the Web app starts, so set it to Load-on-startup Servlet.
  
(2). Specify the configuration file for path configuration Springmvc in Web. xml
  
<?xml version= "1.0" encoding= "UTF-8"?>
  
<beans xmlns= "Http://www.springframework.org/http://www.huazongyule.com/schema/beans"
  
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
  
Xsi:schemalocation= "Http://www.springframework.org/schema/beans
  
Http://www.springframework.org/schema/beans/spring-beans-4.0.xsd ">
  
<!--configuring handle, mapping "/hello" request--
  
<bean name= "/hello" class= "Cn.edu.tju.rico.controller.HelloController"/>
  
<!--processing Mapper looks up the bean's name as a URL and needs to specify name (that is, url) when configuring handle.
  
<bean class= "org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
  
<!--Simplecontrollerhandleradapter is a processor adapter that implements the Handleradapter interface for all processing adapters--
  
<bean class= "Org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
  
<!--View Resolver--
  
<bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver"/>
  
</beans>
  
If we are using XML to configure the SPRINGMVC controller, we need to specify the specific controller and the request URI it handles in the configuration file. The SPRINGMVC core components such as handlermapping, Handleradapter, and Viewresolver can be configured explicitly, or the default configuration of SPRINGMVC can be used. In other words, the above configuration of core components such as handlermapping, Handleradapter, and viewresolver can be removed. SPRINGMVC The default configuration for the above core components is in Dispatcherservlet.properties under the same directory as Dispatcherservlet, as follows:
  
# Default Implementation classes for Dispatcherservlet ' s strategy interfaces.
  
# used as fallback when no matching beans is found in the Dispatcherservlet context.
  
# meant to being customized by application developers.
  
Org.springframework.web.servlet.localeresolver=org.springframework.web.servlet.i18n.acceptheaderlocaleresolver
  
Org.springframework.web.servlet.themeresolver=org.springframework.web.servlet.theme.fixedthemeresolver
  
# Two default handlermapping
  
org.springframework.web.servlet.handlermapping= Org.springframework.web.servlet.handler.beannameurlhandlermapping,\
  
Org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping
  
# three default Handleradapter
  
Org.springframework.web.servlet.handleradapter=org.springframework.web.servlet.mvc.httprequesthandleradapter,\
  
Org.springframework.web.servlet.mvc.simplecontrollerhandleradapter,\
  
Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
  
# three default Exceptionresolver
  
Org.springframework.web.servlet.handlerexceptionresolver= Org.springframework.web.servlet.mvc.annotation.annotationmethodhandlerexceptionresolver,\
  
Org.springframework.web.servlet.mvc.annotation.responsestatusexceptionresolver,\
  
Org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver
  
Org.springframework.web.servlet.requesttoviewnametranslator= Org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator
  
# a default Internalresourceviewresolver
  
Org.springframework.web.servlet.viewresolver=org.springframework.web.servlet.view.internalresourceviewresolver
  
Org.springframework.web.servlet.flashmapmanager=org.springframework.web.servlet.support.sessionflashmapmanager
  
If the developer does not configure components such as handlermapping, Handleradapter, and so on in the Springmvc configuration file, then Dispatcherservlet chooses the appropriate implementation class from the default configuration above for request matching, processing, response, and so on.
  
(3). Implement the controller configured in the SPRINGMVC configuration file
  
public class Hellocontroller implements controller{
  
Public Modelandview HandleRequest (HttpServletRequest request,
  
HttpServletResponse response) throws Exception {
  
Creates a Modelandview object that is ready to be returned, as shown in the name, which typically contains the return view name, model name, and model object
  
Modelandview mv = new Modelandview ();
  
Add model data, which can be any of the Pojo objects
  
Mv.addobject ("message", "Hello, Rico ...");
  
Sets the logical view name that the view resolver resolves to a specific view page based on that name
  
Mv.setviewname ("/web-inf/views/welcome.jsp");
  
Returns the Modelandview object
  
return MV;
  
If we configure the SPRINGMVC controller with XML, then our specific controller must have the Controller interface and invoke the business logic component in the HandleRequest method to process the request and generate the response. The response here is a Modelandview object, and Dispatcherservlet selects the appropriate viewresolver and populates the model with a view based on the Modelandview object to render and return to the user.
  
Note that the implementation class of the Controller interface can only handle a single request action, that is, a controller corresponds to a request. The note-based controller we mentioned later can support processing multiple request actions at the same time, truly implementing method-level request interception and processing.
  
(4). The corresponding view page
  
<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%>
  
<%
  
String path = Request.getcontextpath ();
  
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";
  
%>
  
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >
  
  
  
<base href= "<%=basePath%>" >
  
<title>welcome</title>
  
<meta http-equiv= "Pragma" content= "No-cache" >
  
<meta http-equiv= "Cache-control" content= "No-cache" >
  
<meta http-equiv= "Expires" content= "0" >
  
<meta http-equiv= "keywords" content= "keyword1,keyword2,keyword3" >
  
<meta http-equiv= "description" content= "This is my page" >
  
  
<body>
  
${requestscope.message} <br>
  
</body>
  
  
In the view above, Dispatcherservlet selects the appropriate viewresolver and displays it to the user according to the model that the controller returns, as shown in:
  
xml-page.png-6.1kb
  
2. SPRINGMVC application development Process Demo:annotation configuration
  
(1). Configure the front-end controller in Web. Dispatcherservlet
  
<?xml version= "1.0" encoding= "UTF-8"?>
  
<web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
  
Xmlns= "Http://java.sun.com/xml/ns/javaee"
  
xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  
Id= "webapp_id" version= "2.5" >
  
<display-name>SpringMVCDemo</display-name>
  
<!--Configure Spring MVC's front-end controller: Dispatchcerservlet-
  
<servlet>
  
<servlet-name>springmvc</servlet-name>
  
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  
<!--SPRINGMVC configuration file path and name-
  
<init-param>
  
<param-name>contextConfigLocation</param-name>
  
<param-value>classpath:springmvc.xml</param-value>
  
</init-param>
  
<!--the web app loads as soon as it starts
  
<load-on-startup>1</load-on-startup>
  
</servlet>
  
<servlet-mapping>
  
<servlet-name>springmvc</servlet-name>
  
<url-pattern>/</url-pattern> <!--intercept all requests--
  
</servlet-mapping>
  
</web-app>
  
Dispatcherservlet configuration is the same as SPRINGMVC based on XML configuration, this does not repeat.
  
(2). Specify the configuration file for path configuration Springmvc in Web. xml
  
<?xml version= "1.0" encoding= "UTF-8"?>
  
<beans xmlns= "Http://www.springframework.org/schema/beans"
  
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
  
xmlns:context= "Http://www.springframework.org/schema/context"
  
Xmlns:mvc= "Http://www.springframework.org/schema/mvc"
  
Xsi:schemalocation= "Http://www.springframework.org/schema/beans
  
Http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  
Http://www.springframework.org/schema/context
  
Http://www.springframework.org/schema/context/spring-context-4.0.xsd
  
Http://www.springframework.org/schema/mvc
  
Http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd ">
  
<!--configuring handle, mapping "/hello" request--
  
<!--<bean name= "/hello" class= "Cn.edu.tju.rico.controller.HelloController"/>--
  
<!--spring automatically scans related classes and registers spring annotation classes as spring beans--
  
<context:component-scan base-package= "Cn.edu.tju.rico" ></context:component-scan>
  
<!--processing Mapper looks up the bean's name as a URL and needs to specify name (that is, url) when configuring handle.
  
<!--<bean class= "org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>--
  
<bean class= "org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
  
<!--Simplecontrollerhandleradapter is a processor adapter that implements the Handleradapter interface for all processing adapters--
  
<!--<bean class= "Org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>--
  
<bean class= "Org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
  
<!--View Resolver--
  
<bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver"/>
  
</beans>
  
If we configure the SPRINGMVC controller in a annotation manner, then in the configuration file we first need to scan all the annotation-based controllers classes in the SPRINGMVC application. Notice that the configuration of handlermapping, Handleradapter, we are using requestmappinghandlermapping and requestmappinghandleradapter two implementation classes respectively, Instead of using the corresponding annotation class in the SPRINGMVC default configuration: Defaultannotationhandlermapping and Annotationmethodhandleradapter, This is because the two classes of defaultannotationhandlermapping and annotationmethodhandleradapter have been deprecated by spring.

Spring MVC Brief: Starting with the common concerns of the MVC framework

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.