SPRINGMVC Introduction and HelloWorld Engineering example

Source: Internet
Author: User
Tags exception handling file upload locale map data structure zip

What is MVC?

Model-View-Controller (MVC) is a well-known design pattern based on the design of the interface application. It decouples the business logic from the interface primarily by separating the models, views, and roles of the controller in the application . Typically, the model is responsible for encapsulating application data in the view layer presentation. The view simply shows the data and does not contain any business logic. The controller is responsible for receiving requests from the user and invoking the background service (Manager or DAO) to process the business logic. After processing, the background business layer may return some data to be presented at the view level. The controller collects this data and prepares the model for presentation at the view level. The core idea of the MVC pattern is to separate the business logic from the interface, allowing them to change independently without affecting each other.


What is Spring Web mvc?

Spring Web MVC is a lightweight web framework that implements the request-driven type of the Web MVC design pattern based on Java, that is, the idea of using the MVC architecture pattern, decoupling the WEB layer from the responsibility, and based on the request-driven refers to the use of the request- Response Model , the purpose of the framework is to help us simplify our development, and Spring Web MVC also simplifies our daily web development.

There is also a component-based, event-driven web framework that is not covered here, such as tapestry, JSF, and so on.

Spring Web MVC is also an implementation of service-to-worker mode, but it can be optimized. The front controller is Dispatcherservlet, and the application controller is actually split into the processor mapper (Handler Mapping) and the view Resolver, the former processor management, the latter for the View management; Page Controller (Action/ Processor) is an implementation of the Controller interface (which contains only the model and View HandleRequest (Request,response) method) (or any Pojo class), supports localization (Locale) parsing, Topics (Theme) parsing and file uploading, etc. provide very flexible data validation, formatting, and data binding mechanisms, and provide a powerful contract-like programming support that is larger than the configuration (customary precedence principle).

In spring MVC applications, models are typically composed of Pojo objects, which are processed in the business layer and persisted in the persistence layer. Views are typically JSP templates written in the JSP Standard Tag library (JSTL). The Controller section is responsible for the Dispatcherservlet. What Spring Web mvc can do

√ allows us to design a clean web layer and a thin web layer very simply;

√ The development of a more concise web layer;

√ Natural integration with spring framework (e.g. IOC container, AOP, etc.);

√ Provide a strong contract with more than the configuration of the contractual programming support;

√ Simple Unit Testing of the web layer ;

√ Support flexible URL to page controller mapping;

√ It is very easy to integrate with other view technologies, such as velocity, freemarker, and so on, because the model data is not placed in a particular API, but in a model (map data structure is implemented so it is easily used by other frameworks);

√ Very flexible data validation, formatting and data binding mechanism, can use any object for data binding, do not need to implement a specific framework of the API;

√ Provide a powerful set of JSP tag libraries to simplify JSP development;

√ Support flexible localization, theme and other analysis;

√ More simple exception handling;

√ Support for static resources;

√ Support restful style. Spring Web MVC Architecture

The Spring Web MVC Framework is also a request-driven web framework that is designed with a front-end controller pattern and then distributed to the appropriate page controller (action/processor) based on the request mapping rules. First let's look at the process of Spring WEB MVC processing requests as a whole:

The following steps are performed:

1, the first user sends the request and the front controller, the front controller according to the request information (such as URL) to decide which page controller to process and delegate the request to it, that is, the control logic of the previous controller, the above Figure 1, 2 steps;

2, after the page controller receives the request, carries on the function processing, first needs to collect and binds the request parameter to an object, this object calls the Command object in spring Web MVC, validates, and then delegates the command object to the business object for processing ; Returns a modelandview (model data and Logical view name) after processing; 3, 4, 5 steps in the above diagram;

3, the front controller retract control, and then according to the return of the logical view name, select the corresponding view to render, and the model data passed in so that the view rendering; steps 6, 7 in the image above;

4, the front controller again regain control, return the response to the user, the above figure in step 8;

To solve the above process, the following questions are organized:

1, request how to give the front controller.

2, the front controller how to select the page controller according to the request Information function processing.

3, how to support a variety of page controller it.

4. How the page controller uses the business object.

5. How the page controller returns model data.

6, the front controller how to select a specific view to render according to the logical view name returned by the page controller.

7. How different view technologies use the corresponding model data.

First of all, we know that there are problems, how to solve these problems. Please let us go ahead and answer in turn.

The Dispatcherservlet workflow in Spring Web MVC is shown in figure

The Dispatcherservlet core code is as follows:

Front-End controller dispatch method protected void Dodispatch (HttpServletRequest request, httpservletresponse response) throws Exception {  
        HttpServletRequest processedrequest = Request;  
        Handlerexecutionchain mappedhandler = null;  
        int interceptorindex =-1;  
            try {Modelandview mv;  
  
            Boolean errorview = false; The try {//check is whether the request is a multipart (such as a file upload), if it is resolved by multipartresolver processedrequest = Check  
                   Multipart (Request);  
                Step 2, request to the Processor (page Controller) mapping, mapping through handlermapping Mappedhandler = GetHandler (Processedrequest, false); if (Mappedhandler = = NULL | | Mappedhandler.gethandler () = = null) {Nohandlerfound (proces  
                    Sedrequest, response);  
                Return }//Step 3, processor adaptation, wrapping our processor into the appropriate adapter (thus supporting multiple types of processors) Handleradapter ha = Gethandleradapter  (Mappedhandler.gethandler ());
  
                  304 Not modified cache support//omit specific code here//perform processor-related interceptor preprocessing (Handler  
                Interceptor.prehandle)//omitted here Specific code//step 4, consists Adapter execution processor (call processor corresponding function processing method)  
  
                MV = Ha.handle (processedrequest, Response, Mappedhandler.gethandler ());  
                Do we need view name translation?  
                if (mv! = null &&!mv.hasview ()) {Mv.setviewname (Getdefaultviewname (request));  
            }//Perform processor-related interceptor post-processing (handlerinterceptor.posthandle)//Omit specific code here} catch (Modelandviewdefiningexception ex) {logger.debug ("Modelandviewdefiningexception enc  
                Ountered ", ex);  
            MV = Ex.getmodelandview (); } catch (Exception ex) {Object handler = (Mappedhandler! = null? mappedhandler.gethandle  
                R (): null); MV = ProcesshaNdlerexception (processedrequest, response, Handler, ex);  
            Errorview = (mv! = null);  
			}//Step 5 Step 6, parse view and make view render//Step 5 Parse View by Viewresolver (Viewresolver.resolveviewname (viewName, Locale)) Step 6 View will pass in the model when rendering (View.render (Mv.getmodelinternal (), request, response);) if (mv! = null &&  
                !mv.wascleared ()) {render (MV, processedrequest, response);  
                if (Errorview) {webutils.clearerrorrequestattributes (request); }} else {if (logger.isdebugenabled ()) {Logger.debug ("Null Modelandview returned to Dispatcherservlet with name '" + getservletname () + "': assu  
                Ming Handleradapter completed request handling ");  
        }}//Perform post-processing of processor-related interceptors (handlerinterceptor.aftercompletion)//omit specific code here CaTCH (Exception ex) {//Trigger after-completion for thrown Exception.  
            Triggeraftercompletion (Mappedhandler, Interceptorindex, processedrequest, Response, ex);  
        Throw ex; } catch (Error err) {servletexception ex = new Nestedservletexception ("Handler processing Failed"  
            , err);  
            Trigger after-completion for thrown exception.  
            Triggeraftercompletion (Mappedhandler, Interceptorindex, processedrequest, Response, ex);  
        Throw ex;  
            } finally {//clean up any of the resources used by a multipart request.  
            if (processedrequest! = Request) {Cleanupmultipart (processedrequest);   }  
        }  
    }

The specific process steps are as follows:

1, the first user sends the request->dispatcherservlet, the front controller receives the request not to carry on the processing, but entrusts to the other parser carries on the processing, as the unified access point, carries on the global flow control;

2. Dispatcherservlet->handlermapping,handlermapping will map the request to a Handlerexecutionchain object (containing a handler processor (page Controller) object, Multiple Handlerinterceptor interceptors), through this strategy mode, it is easy to add a new mapping strategy;

3, Handlerexecutionchain->handleradapter,handleradapter will be packaging the processor as an adapter, so as to support a variety of types of processors, the adapter design mode of application, This makes it easy to support many types of processors ;

4, handleradapter-> processor function processing method call, Handleradapter will be based on the results of the adaptation to call the real processor function processing method, complete the function processing, and return a Modelandview object (including model data, logical view name);

5, Modelandview logical view name-->viewresolver,viewresolver will parse the logical view name into a specific view, through this strategy mode, it is easy to replace other view technology;

6, view--> rendering, the view will be based on the model data passed in to render, here the model is actually a map data structure, so it is easy to support other view technology;

7, return control to Dispatcherservlet, by Dispatcherservlet return response to the user, to this end of a process.

Here we just talk about the core process, not consider interceptors, local parsing, file upload parsing, and then detailed. Here, let's look at the questions raised in front of us:

1, request how to give the front controller. This should be described in the deployment description in Web. XML and explained in detail in the HelloWorld engineering example.

2, the front controller how to select the page controller according to the request Information function processing. We need to configure handlermapping for mapping.

3, how to support a variety of page controller it. Configure Handleradapter to support multiple types of page controllers.

4. How the page controller uses the business object. It is expected that the dependency injection function of the spring IOC container must be utilized.

5. How the page controller returns model data. return using Modelandview.

6, the front controller how to select a specific view to render according to the logical view name returned by the page controller. Use Viewresolver for parsing.

7. How different view technologies use the corresponding model data. Because model is a map data structure, it is easy to support other view technologies. Spring Web MVC Advantage

1. Clear role Division: front-end controller (dispatcherservlet), request-to-processor mapping (handlermapping), processor adapter (handleradapter), view resolver (viewresolver), The processor or page controller (Controller), Validator (Validator), the Command object (the object that the command request parameter binds to is called the Commands object), and the Form object (the object that forms object provides to the form to display and submit to is called the form objects).

2, the Division of labor is clear, and the extension point is quite flexible, can easily expand, although almost no need;

3, because the command object is a Pojo, without inheriting the framework-specific API, you can use the command object directly as a business object;

4. Seamless integration with other spring frameworks is not available in other web frameworks;

5, adaptable, through the Handleradapter can support any class as a processor;

6, can be customized, handlermapping, viewresolver and so can be very simple customization;

7, powerful data validation, formatting, binding mechanism;

8. Using the mock object provided by spring can make the Web Layer unit test very simple;

9, localization, the interpretation of the theme of support, making it easier for us to international and theme switching.

10, the powerful JSP tag library, make JSP writing easier.

...... There are support for RESTful styles, simple file uploads, contractual programming support with more than one configuration, annotation-based 0 configuration support, and so on.

Now that we have a simple understanding of spring Web MVC, let's take a look at the next example to use this framework.

Hello World Project

☆ Development tools: Eclipse Java EE

☆ Operating Environment: tomcat8.5

☆ Engineering: Dynamic Web Engineering (project named Springmvc_test)

☆spring Framework Download:

Spring-framework-4.3.5.release-dist.zip

☆ Dependent JAR Package:

1. Spring Framework jar Package:

For simplicity, copy all jar packages under spring-framework-4.3.5.release-dist.zip/libs/to the Web-inf/lib directory of the project;

2. The spring framework relies on the logging and JSTL packages:

Need to add Apache commons logging log, used here is the Version1.2 version of Commons-logging-1.2.jar;

Need to add JSTL tag library support, used here are Taglibs-standard-impl-1.2.5.jar and Taglibs-standard-spec-1.2.5.jar; 1, Front controller configuration

In our web. XML, add the following configuration:

<servlet>  
     <servlet-name>test</servlet-name>  
     	<servlet-class>
 	Org.springframework.web.servlet.DispatcherServlet
   </servlet-class>  
      <load-on-startup>1</ load-on-startup>  
  </servlet>  
  <servlet-mapping>  
     <servlet-name>test</ servlet-name>  
     <url-pattern>/</url-pattern>  
  </servlet-mapping>

Load-on-startup: indicates that the servlet was initialized when the container was started;

Url-pattern: Indicates which requests are given to spring Web MVC processing , and "/" is used to define the default servlet mappings. You can also block all requests that have HTML extensions as "*.html".

Since this request has been handed over to the spring WEB MVC Framework, we need to write the spring configuration file, and the default dispatcherservlet will load the servlet name named "Dispatcherservlet" in the Web-inf directory. Servlet.xml "configuration file. In this example, the Dispatcherservlet name is configured as "test" in the <servlet-name> tag in Dispatcherservlet, so spring's configuration file is web-inf/ Test-servlet.xml.

2. Configure Handlermapping, Handleradapter in the spring configuration file

Specific configuration in the Web-inf/test-servlet.xml file:

<?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.spri Ngframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd Http://www.spri 
      Ngframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd Http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring- Mvc-4.3.xsd "> <!--handlermapping--<bean class=" Org.springframework.web.servlet.handler.BeanNameUrl 

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.