Spring MVC Simple principle

Source: Internet
Author: User

Spring MVC principle

For those with Java Web Foundation, Spring Foundation, and spring MVC experience.

Objective

Currently Java-based Web backend, spring ecology should be more common. Although there is now a popular front-end separation, MVC and back-end template rendering is becoming less common, with the backend focusing on providing data interfaces to the front end. But because the author maintains an old project, both JSP technology and only return JSON interface, both are based on spring MVC This set of technology implementation, so for a moment to find out the Spring MVC principle is helpful.

Spring MVC Workflow

I guess we've all seen this picture for the first time when we learned spring MVC.

After reading this picture, the workflow of Spring MVC is basically a glance. Build the project and then Web. XML with a dispatcherservlet (even the web. XML does not need to be configured, directly through Java classes and @Configuaration configuration), annotations @Controller , @RequestMapping and @Service so on. Match Tomcat in the IDE, OK, and a spring MVC Hello World is running. Asking about the principles of spring MVC, I can also press the workflow in Palawan.

However, this is not so much the theory of spring MVC as the MVC model. How does Spring mvc know to route a request to a method in the corresponding controller? method returns a Modelandview object or even a view name string, and the framework finds a view (such as the most common JSP) with the model and view name. Halfway decent of the author, can be said to be quite curious.

Speaking of Servlets from Servlets, Web. XML, and Web-inf

Java servlet I'm not going to go into this, just look at the annotations of the class.

A servlet is a small the Java program, that runs within a WEB server. Servlets receive and respond to requests from WEB clients, usually across HTTP

The servlet is just a specification that must be deployed to a servlet container to work, of course this article is definitely httpservlet, so the usual containers are Tomcat, jetty, and so on.

See Servlet the interface first, each method's comments see the source code

publicinterface Servlet {    publicvoidinitthrows ServletException;    publicgetServletConfig();    publicvoidservicethrows ServletException, IOException;    publicgetServletInfo();    publicvoiddestroy();}

Where the Init method is called by the container when the servlet is ready to serve the service, and is called only once during the entire life cycle, the Destroy method is, of course, called at the end, and the service method processes the ServletRequest and responds.

Xml

The servlet can accept the request when the servlet is deployed to the servlet container, and how does the container know which request corresponds to which servlet?
OK, our web. XML is on its debut.

<?xmlVersion= "1.0" encoding= "UTF-8"?><web-appxmlns="Http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation="Http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"version="3.1">    <servlet>        <servlet-name>Servlet</servlet-name>        <servlet-class>Com.foo.bar.SomeServlet</servlet-class>    </servlet>    <servlet-mapping>        <servlet-name>Servlet</servlet-name>        <url-pattern>/some/url</url-pattern>    </servlet-mapping></web-app>

As above, the simplest of a Web. XML description file, what does it describe? It should all be understood, someservlet this servlet will handle the URL to/some/url request, this someservlet probably long like this

publicclassextends HttpServlet {    @Override    protectedvoiddoGetthrows ServletException, IOException {        PrintWriter writer = resp.getWriter();        writer.write("hello boys");        writer.flush();        writer.close();    }}

When GET someHost:port/some/url , it will return to Hello Boys. It is not difficult to imagine that the request is more, the servlet node in Web. XML will be more and more, maintenance is also a physical work (of course, the Spring MVC configuration file maintained with the use of the same, not much less, but easier to maintain, because the combination of spring beans, the following again).
The above should be the simplest description of the servlet.

Spring Container Management Bean

This has been used in spring should have some understanding, say my own understanding

The core is DI, which manages the dependencies between the beans through spring, the IOC container, and injects dependencies through spring at startup rather than new when writing code.

There are several classes that I think are more important, and I think it's a good time to see the spring code in tandem:

    • Beandefinition:spring definition, the most common I personally think the best understanding of the XML is defined in the bean, here to worship the spring reserved extension points, otherwise Dubbo beans can be managed through the spring container, right, We'll talk about it later.
    • Beanfactory: Good understanding, the production of Bean factory, not much to say that they look at the code.
    • Applicationcontext:spring context container, the basic use is it, temporarily as a black box, all the beans from here Getbean get on the line, the rest of their own code to see.
Dispatcherservlet

Well, finally to spring MVC, the first one we've seen. Web. XML configuration

<?xmlVersion= "1.0" encoding= "UTF-8"?><web-appxmlns="Http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation="Http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"version="3.1">    <servlet>        <servlet-name>Dispatcher</servlet-name>        <servlet-class>Org.springframework.web.servlet.DispatcherServlet</servlet-class>        <init-param>            <param-name>Contextconfiglocation</param-name>            <param-value>Classpath:applicationContext.xml</param-value>        </init-param>        <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>        <servlet-name>Dispatcher</servlet-name>        <url-pattern>/</url-pattern>    </servlet-mapping></webapp>

Notice a few points:

    • Dispatcherservlet This servlet takes over all the requests (Servlet-mapping's configuration)
    • There is also a load-on-startup in the servlet configuration with a value of 1
    • Init-param here is configured with a parameter contextconfiglocation, whose value is the Spring Bean's configuration file

Dispatcherservlet took over all the requests, OK, see here Everyone is estimated also understand, is in this servlet service method according to different URLs to find different controller to deal with Load-on-startup This parameter specifies that if the value is greater than 0, it will be initialized at startup by the container, and the smaller the value, the lower the initialization order; The Init-param name is straightforward enough to indicate the parameters that the servlet can configure. Visible to the servlet (there is also a context-param, visible to all Servlets, There are other configurable parameters in Web. xml that are interested in self-access, and the value of Contextconfiglication is the multiple-definition Bean-config file.

Finish these, we guess should sorta, summed up is a sentence:
When the servlet container starts, it invokes the Init method in Dispatcherservlet, initializes all beans with spring, and saves a mapping between URLs to Handler
As far as the mapping relationship is, the XML configuration, @RequestMapping which is a concrete implementation, is very well defined. Of course, this is a simple rough summary, the details of the problem has been skipped but you yourself in the Init method to make a breakpoint, debug with, step by step to get the whole process.

The article is relatively short and relatively simple, we may all understand, but I think these points to clear the whole process is still helpful. Several questions have not been answered, I can only say that the answer is in the code, with a full understanding. Write not good everyone also don't laugh, give me more advice, everyone progress on OK.

Spring MVC Simple principle

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.