How does Spring MVC work?

Source: Internet
Author: User
Tags abstract bind file upload html page http request java web apache tomcat maven central
how Spring MVC works.

This is a very good article, for everyone to strengthen the understanding of the SPRINGMVC, spend 5 minutes of your time must look.

This article will delve into a part of the Spring framework--spring the powerful features of WEB MVC and how it works internally.

The source code of this article can be found on GitHub.

HTTPS://GITHUB.COM/BAELDUNG/STACKIFY/TREE/MASTER/SPRING-MVC Project Installation

In this article, we will use the latest, best spring Framework 5. We'll focus on spring's classic web stack, which is emerging from the first version of the framework and is still the primary way to build Web applications with spring. For starters, to install a test project, it's best to use Spring boot and some beginner dependencies, as well as define the parent:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId> spring-boot-starter-parent</artifactid>
    <version>2.0.0.M5</version>
    <relativepath /></parent><dependencies>
    <dependency>
        <groupid>org.springframework.boot </groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId> Spring-boot-starter-thymeleaf</artifactid>
    </dependency></dependencies>

Please note that in order to use Spring 5, we also need to use Spring Boot 2.x. As of this writing, this is still a milestone release and can be found in spring Milestone repository. Let's add this repository to your MAVEN project:

<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>spring milestones</name>
        <url>https://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository></repositories>

You can view the current version of Spring boot on Maven Central. Sample Project

To understand how spring WEB MVC works, we will implement a simple application through a login page. In order to display the login page, we need to create a @controller annotation class Internalcontroller with a get map for the upper and lower root.

The hello () method is parameter-free. It returns a string that is interpreted by spring MVC as the view name (in the example, the login.html template):

Import org.springframework.web.bind.annotation.GetMapping;
@GetMapping ("/")
Hello () {
return "login"; }

In order to handle user logons, you need to create another way to use the Logon data processing POST request. The user is then redirected to a successful or failed page based on the results.

Note that the login () method receives the domain object as a parameter and returns the Modelandview object:

Import org.springframework.web.bind.annotation.PostMapping;
Import Org.springframework.web.servlet.ModelAndView;
@PostMapping ("/login")
Login (Logindata Logindata) {
if (Login.equals (Logindata.getlogin ()) && password.equals (Logindata.getpassword ())) {
return new Modelandview ("Success", collections.singletonmap ("Login", Logindata.getlogin ())); } else {
return new Modelandview ("Failure", collections.singletonmap ("Login", Logindata.getlogin ());} }

Modelandview is a holder of two different objects:

model--Key-value mappings for rendering page data

view--page templates for populating model data

These are connected for convenience, so that the Controller method can return them at once.

To render an HTML page, use Thymeleaf as the View template engine, which has a reliable and out-of-the-box integration with spring. servlet as the basis for Java Web applications

Then, when you enter http://localhost:8080/in the browser, press ENTER, and then the request arrives at the Web server and what actually happens. How do you see the Web form in the browser from this request.

Since the project is a simple spring boot application, it can be run through spring5application.

Spring Boot uses Apache Tomcat by default. Therefore, when you run the application, you may see the following information in the log:

2017-10-16 20:36:11.626  INFO 57414---[main] 
  o.s.b.w.embedded.tomcat.tomcatwebserver  : 
  Tomcat Initialized with Port (s): 8080 (http)
2017-10-16 20:36:11.634  INFO 57414---[main] 
  O.apache.catalina.core.standardservice   : 
  starting service [Tomcat]
2017-10-16 20:36:11.635  INFO 57414---[main] 
  org.apache.catalina.core.StandardEngine  : 
  starting Servlet Engine:apache tomcat/ 8.5.23

Because Tomcat is a servlet container, every HTTP request sent to the Tomcat Web server is naturally handled by the Java servlet. So the Spring Web application entry point is a servlet, which is not surprising.

In short, the servlet is the core component of any Java Web application; it is low-level and does not require much in a particular programming pattern like MVC.

An HTTP servlet can only receive one HTTP request, process it in some way, and then send back a response.

And, starting with the Servlet 3.0 API, you can now go beyond the XML configuration and start leveraging the Java configuration (with only a small limit). Dispatcherservlet as the core of spring MVC

As a developer of a Web application, what we really want to do is abstract the following tedious and templated tasks and focus on useful business logic:

Mapping HTTP requests to a processing method

Resolves HTTP request data and headers to data transfer objects (DTOS) or domain objects

Model – View – Controller integration

Generate responses from DTOs, domain objects, etc.

Spring Dispatcherservlet is able to provide these. It is the core of the spring WEB MVC framework, and this core component receives all requests to the application.

As you can see, the dispatcherservlet is very extensible. For example, it allows you to insert different existing or new adapters for a number of tasks:

Map the request to the class or method that should handle it (implementation of the Handlermapping interface)

Processing requests using specific patterns, such as regular servlets, more complex MVC workflows, or methods in the Pojo bean (Implementation of the Handleradapter interface)

Resolve views by name, allowing you to use different template engines, xml,xslt or any other view technology (implementation of the Viewresolver interface)

Parse multi-part requests by using the default Apache Commons file upload implementation or writing your own multipartresolver

handle HTTP requests using any localeresolver implementation of the language environment, including cookies, sessions, Accept HTTP headers, or any other way to determine the desired locale for the user

First, we traced the processing of a simple HTTP request to a method in the controller layer and then returned to the browser/client.

Dispatcherservlet has a long inheritance hierarchy, and it is valuable to understand them from top to bottom. The request processing method is most interesting to us.

Understanding HTTP requests, both locally and remotely in standard development, is a critical part of understanding the MVC architecture. Genericservlet

Genericservlet is part of the servlet specification and does not directly focus on HTTP. It defines the service () method that receives incoming requests and generates a response.

Note how the ServletRequest and Servletresponse method parameters are independent of the HTTP protocol:

Service (ServletRequest req, servletresponse Res) 
 Throws Servletexception, IOException;

This is the method that is eventually called to the server by any request, including a simple GET request. HttpServlet

As the name implies, the HttpServlet class is the HTTP-based servlet implementation defined in the specification.

More realistically, HttpServlet is an abstract class that has a service () method implementation that implements the service () method to split the request over an HTTP method type, roughly as follows:

Service   (HttpServletRequest req, HttpServletResponse resp)
 Throws Servletexception, IOException {
    String method = Req.getmethod ();    
if (Method.equals (Method_get)) { //... Doget (req, resp); } else if (method.equals (Method_head)) { //... Dohead (req, resp); } else if (method.equals (method_post)) { doPost (req, resp); // ... }
Httpservletbean

Next, Httpservletbean is the first Spring-aware class in the hierarchy. It injects the Bean's properties using the servlet Init-param value received from Web. xml or Webapplicationinitializer.

In the case of requesting an application, methods such as doget (), DoPost () are called on a specific HTTP request. Frameworkservlet

The Frameworkservlet integrates the Servlet functionality with the Web application context and implements the Applicationcontextaware interface. However, it is also able to create Web application contexts on its own.

As you've already seen, the Httpservletbean class injects init-params into the bean attribute. Therefore, if a context class name is provided in the servlet's Contextclass Init-param, an instance of the class will be created as an application context. Otherwise, the default Xmlwebapplicationcontext class is used.

Because the XML configuration is now obsolete, Spring boot uses Annotationconfigwebapplicationcontext to configure Dispatcherservlet by default. But you can easily change it.

For example, if you need to configure a spring WEB MVC application using a groovy-based application context, you can use the following Dispatcherservlet configuration in the Web. xml file:

Dispatcherservlet
        org.springframework.web.servlet.DispatcherServlet
        contextclass
        Org.springframework.web.context.support.GroovyWebApplicationContext

Using the Webapplicationinitializer class, you can accomplish the same configuration in a more modern Java-based manner. Dispatcherservlet: Unified Request Processing

The Httpservlet.service () implementation, which routes the request based on the type of the HTTP verb, is very meaningful in the context of the low-level servlet. However, at the abstraction level of spring MVC, method types are just one of the parameters that can be used to map requests to their handlers.

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.