Spring MVC

Spring MVC is currently the mainstream enterprise-level development framework to implement THE MVC design pattern. As a sub-module of Spring framework, it is more convenient to develop without integrating Spring.

What is the MVC design pattern?

The application program is divided into Controller, Model and View. Controller receives client requests and calls Model to generate business data, which is passed to View.

Spring MVC is the encapsulation of this process, shielding a lot of low-level code and opening the outbound interface, so that developers can more easily and conveniently complete Web development based on MVC design pattern.

The core component of Spring MVC

  • DispatcherServlet: front controller, is the core of the whole process control, control the execution of other components, unified scheduling, reduce the coupling between components, equivalent to the commander in chief;
  • Handler: A processor that performs specific business logic. It is equivalent to a Servlet.
  • HandlerMapping: After receiving requests, the DispatcherServlet uses HandlerMapping to map different requests to different handlers.
  • HandlerInterceptor: a processor interceptor, which is an interface that can be implemented if some intercepting needs to be done;
  • HandlerExecutionChain: a processor execution chain consisting of a Handler and a HandlerInterceptor (the system has a default HandlerInterceptor, but if additional interceptors are needed, you can add them).
  • HandlerAdapter: Before the Handler executes a business method, it needs to perform a series of operations, including form data validation, data type conversion, form data encapsulation into a JavaBean, etc. These operations are completed by the HandlerAdapter. Developers only need to focus on the processing of business logic (adapter design pattern). DispatcherServlet executes different handlers through HandlerAdapter.
  • ModelAndView: loaded with model data and view information, which is returned to DispatcherServlet as the processing result of Handler;
  • ViewResolver: A view parser that DispatcherServlet uses to parse the logical view into a physical view and render the result back to the client.

The Spring MVC workflow

  • Client requests are received by DispatcherServlet;
  • Map to Handler according to HandlerMapping;
  • Generate Handler and HandlerInterceptor;
  • Both the Handler and HandlerInterceptor are returned to the DispatcherServlet as HandlerExecutionChain;
  • DispatcherServlet through HandlerAdapter to call Handler methods to complete business logic processing;
  • Handler returns a ModelAndView to the DispatcherServlet;
  • The DispatcerServlet passes the obtained ModelAndView object to the ViewResolver View parser, and resolves the logical View into the physical View View.
  • ViewResolver returns a View to the DispatcherServlet;
  • The DispatcherServlet renders the View according to the View (populating the View View with the Model data Model);
  • The DispatcherServlet responds to the rendered result to the client.

The Spring MVC process is very complex and very simple in practice, because most components do not need to be created and managed by developers. They only need to be configured through configuration files, and only handlers and Views need to be dealt with by developers.

How to use it?

  • Create Maven project, pom.xml;

(If the project name is not displayed on the left of the IDEA tool, close IDEA, delete the. IDEA folder, and open IDEA again.)

(Use webApp template to create the Web project directory, SRC /main/webapp, Java source directory and resources resource directory need to be created by yourself)

<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> The < version > 5.2.9. RELEASE < / version > < / dependency > < / dependencies >Copy the code
  • Configure DispatcherServlet in web.xml;
<? The XML version = "1.0" encoding = "utf-8"? > <web-app xmlns="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_4_0.xsd" Version = "4.0" > < servlet > < servlet - name > dispatcherServlet < / servlet - name > <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>Copy the code
  • springmvc.xml
<? The 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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <! --> <context:component-scan base-package="org.westos"></context:component-scan> <! - the parser configuration view - > < bean class = "org. Springframework. Web. Servlet. The InternalResourceViewResolver" > < property name = "prefix" value="/"/> <! - value = "/" represents the root directory - > < property name = "suffix" value = "JSP" / > < / bean > < / beans >Copy the code
  • Create a Handler
package org.westos.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * @author lwj * @date 2020/12/13 22:29 */ @Controller public class HelloHandler { @RequestMapping("/index") public String index() {system.out.println (" execute index... ); return "index"; }}Copy the code
  • Configure the Tomcat server. Start, run, and successful.

http://localhost:8080/index

Spring MVC annotations

  • @RequestMapping

Spring MVC uses @RequestMapping annotation to map URL requests to business methods. @RequestMapping can be added to Handler’s class definition and method definition. Adding @RequestMapping to the class definition is equivalent to adding a layer of access path to the client.

  • @Controller

@Controller is added at the class definition, handing the class over to the IoC container to manage (in conjunction with springMVC.xml’s auto-scan configuration), and making it a Controller that can receive client requests;

package org.westos.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; /** * @author lwj * @date 2020/12/13 22:29 */ @Controller @RequestMapping("/hello") public class HelloHandler { @requestMapping ("/index") public String index() {system.out.println (" execute index... ); return "index"; }}Copy the code

http://localhost:8080/hello/index

  • @requestMapping Specifies parameters

1. Value: specifies the actual URL request address, which is the default value of @requestMapping.

@requestMapping ("/index") public String index() {system.out.println (" execute index... ); return "index"; }Copy the code

Is equal to the

@requestMapping (value = "/index") public String index() {system.out.println (" execute index... ); return "index"; }Copy the code

2. Method: Specifies the method type of the request, including GET, POST, PUT, and DELETE.

@requestMapping (value = "/index", method = requestmethod.get) public String index() {system.out.println (" execute index... ); return "index"; }Copy the code

The above code indicates that the index method can only receive GET requests.

Use the Postman tool to simulate a POST request to access the index method.

Params: Specifies that the request must contain certain parameters or the method cannot be called.

@RequestMapping(value = "/index", method = RequestMethod.GET, params = {"name", "Id =5"}) public String index() {system.out.println (" execute index... ); return "index"; }Copy the code

The above code means that the request must contain both name and ID, and the value of ID must be 5.

http://localhost:8080/hello/index?name=zhangsan&id=5

For parameter binding, the mapping of HTTP request parameters to business method parameters is done by adding the @requestParam annotation to the parameter list.

(You don’t need to add @requestParam annotations when the request parameter name matches the method parameter name.)

@RequestMapping(value = "/index", method = RequestMethod.GET, params = {"name", "id=5"}) public String index(@RequestParam("name") String str, @requestParam ("id") int age) {system.out.println (" execute index... ); System.out.println(str); System.out.println(age); return "index"; }Copy the code

This code assigns the request parameters name and ID to STR and age, respectively. It also automatically converts the string “10” to an int of type 10 and assigns age, all of which is done by the HandlerAdapter.

Spring MVC also supports RESTful urls.

The traditional type: http://localhost:8080/hello/index? name=zhangsan&id=5

RESTful: http://localhost:8080/hello/rest/zhangsan/10

@RequestMapping(value = "/rest/{name}/{id}")
public String rest(@PathVariable("name") String name, @PathVariable("id") int id) {
    System.out.println(name);
    System.out.println(id);
    return "index";
}

Copy the code

Mapping request parameters to parameters is done using the @pathVariable annotation.

  • Mapping the Cookie

Spring MVC can get Cookie values directly in business methods through mapping.

@RequestMapping(value = "/cookie")
public String cookie(@CookieValue(value = "JSESSIONID") String sessionId) {
    System.out.println(sessionId);
    return "index";
}

Copy the code
  • Bind parameters using JavaBean

Spring MVC automatically matches request parameter names with JavaBean property names, automatically populates the object with property values, and supports cascading properties.

package org.westos.entity;

import lombok.Data;

/**
 * @author lwj
 * @date 2020/12/19 15:57
 */
@Data
public class Address {
    private String value;
}

Copy the code
package org.westos.entity;

import lombok.Data;

/**
 * @author lwj
 * @date 2020/12/19 15:58
 */
@Data
public class User {
    private long id;
    private String name;
    private Address address;
}

Copy the code
<%@ page contentType="text/html; Charset =UTF-8" language=" Java "%> < HTML > <head> <title> title </title> </head> <body> <% <form action="/hello/register" method="post"> <label for="id"> </label> <input type="text" name="id" id="id"> <br> <label for="name"> </label> <input type="text" name="name" id="name"> <br> <label for="value"> </label> <input type="text" name="address.value" id="value"> <br> <input type="submit" value=" registration "> </form> </body> </html>Copy the code
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(User user) {
    System.out.println(user);
    return "index";
}

Copy the code

Add the Spring MVC filter to web.xml.

<filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Copy the code

JSP page forwarding and redirection

By default, Spring MVC responds to a JSP page in the form of a forward.

  1. forwarding
@RequestMapping("/forward")
public String forward() {
    return "forward:/index.jsp";
    //return "index";
}

Copy the code
  1. redirect
@RequestMapping("/redirect")
public String redirect() {
    return "redirect:/index.jsp";
}
Copy the code

conclusion

In addition, HERE I prepared for you the first line of factory interview materials and my original super core PDF technical documents, as well as I prepared for you a number of sets of factory interview questions (constantly updated), welcome to pay attention to the public account: future bright receive! Hope you all find your dream job!