Spring MVC 5.1, Spring MVC start

Source: Internet
Author: User

In the HTTP protocol-based Web application, Spring MVC moves the user request between the dispatch servlet, the processor map, the controller, and the view resolver, and then returns the user results to the user.

We'll show how requests are initiated from the client, through the components in spring MVC, and finally back to the client.

1. Tracking requests from spring MVC

0, Request: When the request leaves the browser, with the user request content information. Typically contains the requested URL, user-submitted form information, and so on.

1, Front controller: Front controller is a common Web application pattern. The server uses a singleton servlet (Spring Dispatcherservlet) as the front-end controller to delegate the request to other components of the application to perform the actual processing.

2. Query map and distribute the request: Dispatcherservlet's task is to send a request to the Spring MVC controller. Dispatcherservlet receives the request, according to the request carries the URL information, queries the processor mapping, determines the request corresponding controller, and sends to the controller.

3, the controller handles the request: After the controller gets the request, it obtains the information submitted by the user in the request, and waits for the controller to process the information.

4. Model and view name: When the controller finishes processing the data, it produces some information (called a model) that needs to be sent to a view for display. The controller packages the model data and marks the name of the view used to render the output, and then sends the request, model, and view logical names back to the Dispatcherservlet

5. View parser: Dispatcherservlet Find the true view implementation based on the logical view name.

6, view rendering: According to the found view implementation, and the model data delivery to the view implementation, you can render the data input.

7, passed to the client: This output is passed to the client through the response object.

2, build spring MVC2.1, configuration Dispatcherservlet

Traditional way: Configured in Web. XML, this file is placed in the application's war package.

Now method: Use Java to configure Dispatcherservlet in the servlet container.

 Public classSpitterwebinitializerextendsAbstractannotationconfigdispatcherservletinitializer {@OverrideprotectedClass<?>[] getrootconfigclasses () {return NewClass<?>[] {rootconfig.class }; } @OverrideprotectedClass<?>[] getservletconfigclasses () {return NewClass<?>[] {webconfig.class};//specifying a configuration class} @Overrideprotectedstring[] Getservletmappings () {return NewString[] {"/"};//map Dispatcherservlet to "/"  }}

Any class that extends Abstractannotationconfigdispatcherservletinitializer automatically configures the Dipatcherservlet and spring application contexts, The application context for spring is within the servlet context of the application.

The Getservletmappings () method maps one or more paths to dispatcherservlet. In this example, "/", which represents the default servlet for the app, handles all requests that go into the app.

To understand the other 2 methods, you need to first understand the relationship between Dispatcherservlet and a servlet listener (contextloaderlistener).

2.2. The relationship between two application contexts

When Dispatcherservlet is started, a spring application context is created to load the bean declared in the configuration file or configuration class.

The Getservletconfigclasses () method requires that the bean that is defined in the Webconfig configuration class be used when the application context is dispatcherservlet loaded.

Contextloaderlistener will create another application context

We want Dispatcherservlet to record beans that contain Web components, such as controllers, view resolvers, and processor mappings, and contextloaderlistener to load other beans in the application, typically the middle tier and data-tier components that drive the backend of the application.

Abstractannotationconfigdispatcherservletinitializer will create both Dispatcherservlet and Contextloaderlistener.

The class with @configuration annotations returned by the Getservletconfigclasses () method is used to define the bean that dispatcherservlet the context of the application.

The class with @configuration annotations returned by the Getrootconfigclasses () method will be used to configure the bean in the context of the app Contextloaderlistener created.

The Servlet3.0 server can only support the configuration of Web. XML, and Servlet3.0 and later versions only support the Abstractannotationconfigdispatcherservletinitializer configuration method.

2.3. Start Spring MVC

Legacy approach: Configure Spring MVC components with XML

Now method: Use Java to configure Spring MVC components

The simplest spring MVC configuration

@Configuration @enablewebmvc  Public class Webconfig {}

This enables spring MVC to start, but the following issues are true:

1. Without configuring the View resolver, Spring uses the default beannameviewresolver, which looks for the bean with the ID matching the view name, and the lookup bean implements the view interface in such a way that it resolves the views.

2, no boot component scan. Causes spring to find only the controllers that are explicitly declared in the configuration class.

3. Dispatcherservlet is mapped to the default servlet, so all requests are processed, including requests for static resources, slices, and style sheets (which are not generally desirable).

The following configuration can solve the above problem

@Configuration @enablewebmvc//Enable Spring MVC@ComponentScan ("Spittr.web")//Enable component Scanning Public classWebconfigextendsWebmvcconfigureradapter {@Bean PublicViewresolver Viewresolver () {//Configuring the JSP View interpreterInternalresourceviewresolver resolver =NewInternalresourceviewresolver (); Resolver.setprefix ("/web-inf/views/"); Resolver.setsuffix (". JSP"); returnResolver; } @Override Public voidconfiguredefaultservlethandling (Defaultservlethandlerconfigurer configurer) {configurer.enable (); } @Override Public voidAddresourcehandlers (Resourcehandlerregistry registry) {//Configuring static resource handling//TODO auto-generated Method Stub    Super. Addresourcehandlers (registry); }}

1, @ComponentScan annotations, will scan the Spittr.web package lookup components, usually we write the controller will use @controller annotations, so that its written component scanning Houxuanbean. So we don't need to explicitly declare any controllers in the configuration class.

2, Viewresolver Bean. It will be discussed in detail later, which is to find the JSP file. For example, home view will be resolved to/web-inf/views/home.jsp.

3. The new Webconfig class expands the webmvcconfigureradapter and re-writes its configuredefaultservlethandling () method. Calling the Enable () method requires Dispatcherservlet to forward requests for static resources to the default servlet in the servlet container instead of using the Dispatcherservlet itself to handle such requests.

Configuration of the RootConfig

@Configration @componentscan (basepackages={"Spitter"},    excludefilters={        @filter { Type=filtertype.annotation, Value=enablewebmvc. class )    })publicclass  rootconfig{}

Spring MVC 5.1, Spring MVC start

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.