The fifth chapter builds spring Web application--SPRINGMVC start

Source: Internet
Author: User

tracking requests from spring MVC

Note: process:

1) The first stop requested to leave the browser is the front-end controller , where a singleton servlet will request delegates to other components of the application to perform the actual processing. Dispatcherservlet is the front-end controller in spring MVC (front controllers).

2) Dispatcherservlet sends the request to the controller of Spring MVC, the controller is the spring component for processing the request, and one (more) controller in an application. But Dispatcherservlet needs to know which controller to send the request to, so Dispatcherservlet will query for one (many) processor mappings (handler Mapping) to determine where the next stop is going. The processor map makes decisions based on the URL information that is carried by the request.

3) Once the appropriate controller is selected, Dispatcherservlet will send the request to the selected controller. To the controller, the request unloads its payload (carrying user information) and waits patiently for the controller to process the information. In fact, the well-designed controller itself deals with little or no work, but instead delegates the business logic to one (many) service objects for processing.

4) After the controller completes the logic processing, the information is generated, which is returned to the user and displayed on the browser. This information is called the model, and the information is sent to a view.

In fact, if the front-end separation is used, then the backend will not return the view, only the JSON data will be returned to the front-end interaction.

5) The final step of the controller is to package the data model and indicate the name of the view used to render the output. It then sends the request to the Dispatcherservlet with the model and view name so that the controller is not coupled to a particular view, and the view name passed to Dispatcherservlet does not directly represent a particular JSP. In fact, it is not certain that the view is a JSP. Instead of just passing a logical name, the name finds and produces a real view. Dispatcherservlet uses the view parser to convert the logical name into a real view.

7) Dispatcherservlet has successfully rendered the view, and the request will be delivered to the model data. The requested task is complete. The view renders the output using the model data, which is passed to the client through the response object.

Build Spring MVCConfigure Dispatcherservlet

With the help of the SERVLET3 specification and Spring3.1, we can implement the Dispatcherservlet configuration in the servlet container instead of using Web. Xml.

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

In the Servlet3.0 environment, the container looks for classes that implement the Javax.servlet.ServletContainerInitailizer interface in the classpath. If there is one, it will be used to configure the servlet container.

Spring provides the implementation of this class: Springservletcontainerinitializer, which in turn finds classes that implement Webapplicationinitializer and gives them the configured tasks.

In Spring3.2 again introduced a Webapplicationinitializer basic realization, this is abstractannotationconfigdispatcherservletinitializer.

Our own Webappinitializer realized the Abstractannotationconfigdispatcherservletinitializer, So as soon as you deploy to the Servlet3.0 container, the container will automatically discover him and use it to discover the servlet context.

Just rewrite one of the three methods to be OK.

Getservletmappings (), which maps one (many) paths to Dispatcherservlet.

Getrootconfigclasses (): Load

Getservletconfigclasses ():

the relationship between two application contexts

Dispatcherservlet and Contextloaderlistener.

The context of the Dispatcherservlet load is the context of the current servlet. A bean that loads a Web component, such as a controller, a view resolver, and a processor mapper.

The context in which Contextloaderlistener is loaded is the global context. Typically, the middle-tier or data-tier components that drive the backend of the application are loaded.

Note: Dispatcherservlet can be implemented more, each dispatcherservlet has its own context, which is obtained through getservletconfigclasses (). And for the entire application there is its own context, and this context is loaded by Contextloaderlistener.

Abstractannotationconfigdispatcherservletinitializer will create both Dispatcherservlet and Contextloaderlistener.

Getservletconfigclasses () returns the bean with the @configuration annotation that will be used to define the Dispatcherservlet application context.

Getrootconfigclasses () returns the bean with the @configuration annotation that will be used to define the application context created by Contextloaderlistener.

In this case, the root configuration is defined in RootConfig, and Dispatcherservlet's configuration is declared in Webconfig.

Enable Spring MVC

Simplest SPRINGMVC configuration (class with @enablewebmvc annotations):

@Configuration @enablewebmvc  Public class Webconfig {}

You can run the SPRINGMVC through it, but there are still problems to be solved.

1) No view parser. Spring defaults to using Beannameview-resolver, which looks for the bean whose ID matches the view name, and the bean to be found to implement the View interface, which parses the view in such a way.

2) No boot component scan. Spring can only find controllers that show claims in the configuration class.

3) Dispatcherservlet is mapped to the application default servlet, which handles requests, including static resources.

Modify: Minimal but available SPRINGMVC configuration.

@Configuration//Enable SPRINGMVC@EnableWebMvc//Enable component Scanning@ComponentScan ("Com.learn.spring.five.dispatcherservlet.web") Public classWebconfigextendswebmvcconfigureradapter{//Configuring the JSP view resolver@Bean Publicviewresolver Viewresolver () {internalresourceviewresolver resolver=NewInternalresourceviewresolver (); Resolver.setprefix ("Web-inf/views/"); Resolver.setsuffix (". JSP"); Resolver.setexposecontextbeansasattributes (true); returnResolver; }    //Configuring the handling of static resources@Override Public voidconfiguredefaultservlethandling (Defaultservlethandlerconfigurer configurer) {configurer.enable (); }}

We have added @componentscan annotations that can be used to find components for the corresponding package. We can implement the Controller component with @controller annotations.

Add the Viewresolver bean, in fact, is internalresourceviewresolver, this view parser will help us find the JSP file, and will help us to add a prefix.

Extended the Webmvcconfigureradapter and Configuredefaultservlethandling () method, using the Enable () method of the Defaultservlethandlerconfigurer , Dispatcherservlet forwards requests for static resources to the default servlet in the Servlet container, rather than dispatcherservlet itself to handle such methods.

This chapter focuses on Web development, and RootConfig is relatively straightforward:

= {"com"},        = {            = Filtertype.annotation,value = Enablewebmvc.  Class)        })publicclass  rootconfig {}
Simulation Background

User (app user) and state (the status of the users publishing).

An application background similar to Weibo.

Fifth build Spring Web application--springmvc 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.