Spring MVC learning notes

1, Introduction

(1) Concept of MVC

MVC is a software architecture idea, which divides software into "model", "view" and "controller"

M: Model, model layer

​ Refers to the "JavaBean" in the project, which is used to process data

​ There are two types of JavaBean s:

​ ❶ entity class Bean: refers to a pojo object that stores business data

​ ❷ business processing Bean: refers to a Service or Dao object that handles business logic and data access

5: V iew, View layer

​ Refers to the "page" in the project, which is used to interact with users and display data

C: Controller, control layer

​ Refers to the "Servlet" in the project, which is used to receive requests and respond to browsers

(2) The concept of spring MVC

Spring MVC is a follow-up product of spring and a subproject of spring

Spring MVC is a complete set of solutions provided by spring for presentation layer development

Note: the three-tier architecture includes presentation layer, business logic layer and data access layer. The presentation layer includes foreground pages and background servlet s

(3) Characteristics of spring MVC

  1. The native products of Spring family are seamlessly connected with infrastructure such as IOC container
  2. Based on the native Servlet, the request and response are processed uniformly through the powerful front-end controller dispatcherservlet
  3. The problems to be solved in each subdivided field of the presentation layer are covered in an all-round way to provide comprehensive solutions
  4. The code is fresh and concise, which greatly improves the development efficiency
  5. High degree of internal componentization, plug and play of pluggable components
  6. Outstanding performance, especially suitable for modern large and super large Internet projects

2, Development process

(1) Introduce dependency

    <!-- SpringMVC --> 
    <!-- journal --> 
    <!-- ServletAPI --> 
    <!-- Spring5 and Thymeleaf Integration package --> 

(2) Configure web xml

Front end controller of spring dispatcher MVC

1. Default configuration method

The default location is under WEB-INF

Default name, < servlet name > - servlet xml

<!-- to configure SpringMVC Front end controller -->
    <!--  /      Mismatch.jsp Request for request path -->
    <!--  /*     Requests that match all request paths -->

2. Extended configuration mode

< init param >, set the "location" and "name" of the configuration file

< load on startup >, set the initialization time

    <!-- Specified by initialization parameters SpringMVC Location and name of the configuration file -->
        <!-- contextConfigLocation Is a fixed value -->
        <!-- Storage path of configuration file src/main/resources -->
    <!-- DispatcherServlet The initialization time of is advanced to the time when the server starts -->

(3) Create request controller

public class HelloController {

    @RequestMapping("/")	//Set access path
    public String index() {
        return "index";		//Return view name

(4) Create MVC profile

<!-- Automatic scanning package -->
<context:component-scan base-package="com.atguigu.mvc.controller"/>

<!-- to configure Thymeleaf view resolver  -->
<bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
    <property name="order" value="1"/>
    <property name="characterEncoding" value="UTF-8"/>
    <property name="templateEngine">
        <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
            <property name="templateResolver">
                <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                    <!-- View prefix -->
                    <property name="prefix" value="/WEB-INF/templates/"/>
                    <!-- View suffix -->
                    <property name="suffix" value=".html"/>
                    <property name="templateMode" value="HTML5"/>
                    <property name="characterEncoding" value="UTF-8" />

<!-- open mvc Annotation driven -->
        <!-- Processing response Chinese content garbled code -->
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <property name="defaultCharset" value="UTF-8"/>
            <property name="supportedMediaTypes">

3, @ RequestMapping

(1) Overview

Function: associate the request with the controller method of processing the request and establish the mapping relationship

Annotation location:

​ ❶ identify a class: set the initial information of the request path of the mapping request

​ ❷ identify a method: set the specific information of the request path of the mapping request

(2) Attributes

1. value attribute

This property must be set

The value attribute of the annotation matches the request mapping through the request address of the request

The value attribute of the annotation is an array of string type, which can map multiple request addresses

2. method property

The method attribute of the annotation matches the request mapping through the request mode of the request

The method attribute of the annotation is an array of RequestMethod type, which can match multiple

1. The requested address satisfies the value attribute but not the method attribute. 405 error: Request method 'POST' not support

2. Spring MVC provides a derived annotation of @ RequestMapping for the controller method that handles the specified request

​ @GetMapping,@PostMapping,@PutMapping,@DeleteMapping

3. params attribute

The params attribute of the annotation matches the request mapping through the request parameters of the request

The params property of the annotation is an array of string type, with four kinds of setting expressions

​ ❶ "param": the request must carry param parameters

​ ❷⏳⏳! Param]: the request must not carry param parameters

​ ❸ "param=value": the request must carry the param parameter, and the value is value

​ ❹ "param!=value": the request must not carry param parameters, and the value is not value

The requested address satisfies the value and method attributes, but does not satisfy the parameters attribute, 400 error, parameter conditions not met for actual request parameters

4. headers property

The headers attribute of the annotation matches the request mapping through the request header information of the request

The headers attribute of the annotation is an array of string type, with four kinds of setting expressions

​ ❶ "header": the request must carry the header information

​ ❷  header: the request must not carry header information

​ ❸ "header=value": the request must carry the header information and the value is value

​ ❹ "header!=value": the request must not carry header request header information, and the value is not value

The requested address satisfies the value and method attributes, but does not satisfy the headers attribute, 404 error, and the resource is not found

(3) value attribute supplement

1. ant style path supported

Fuzzy matching

​ 『 ? 』: Represents any single character

​ "*": represents any 0 or more characters

​ [ * * ]: refers to any 0-layer or multi-layer directory [only / * * / xxx can be used]

2. Supports placeholders in paths

Placeholders in the spring MVC path are often used in RESTful style. When some data is transferred to the server through the path in the request path

The transmitted data can be represented by placeholder {xxx} in the value attribute of the corresponding @ RequestMapping annotation

Then assign the data represented by the placeholder to the formal parameters of the controller method through the @ PathVariable annotation

//Request path: / testRest/1/admin
public String testRest(@PathVariable("id")Integer id, @PathVariable("username")String username) {
    System.out.println("id = " + id);
    System.out.println("username = " + username);
    return "success";

4, Get parameters

1. Get through servlet API

Premise: take HttpServletRequest as the formal parameter of the controller to obtain parameters

public String testServletAPI(HttpServletRequest request) {
    String username = request.getParameter("username");
    System.out.println("username = " + username);
    return "success";


2. Get the formal parameters of the controller method

Premise: set the formal parameter with the same name as the request parameter at the formal parameter position of the controller method, and the parameter and assignment can be automatically matched

//Request address: / testparam? username=admin&hobby=a&hobby=b
public String testParam(String username, String[] hobby) {
    System.out.println("username = " + username);
    System.out.println("hobby = " + Arrays.toString(hobby));
    return "success";

If there are multiple request parameters with the same name in the request, the formal parameter can be set to string type or string array type

String type: concatenate with commas


Function: create a mapping relationship between the request parameters and the formal parameters of the controller method

Annotations have three properties:

​ ❶ "value": specify the parameter name in the request parameters

​ ❷ required: set whether transmission is required. The default value is true

​ ❸ 「 defaultValue 」: set the default value when there is no input or "" input

public String testParam(
        @RequestParam(value = "user_name", required = false, defaultValue = "he") 
    		String username) {
    System.out.println("username = " + username);
    return "success";


Function: create a mapping relationship between the request header information and the formal parameters of the controller method

public String testParam(@RequestHeader(value = "Host") String host) {
    System.out.println("host = " + host);
    return "success";


Function: create mapping relationship between cookie data and formal parameters of controller method

public String testParam(@CookieValue("JSESSIONID") String JSESSIONID) {
    System.out.println("JSESSIONID = " + JSESSIONID);
    return "success";

6. Obtained through POJO

Premise: when the parameter name of the request parameter transmitted by the browser is consistent with the attribute name in the entity class, the request parameter will be assigned to this value

public String testBean(User user) {
    return "success";
//User{id=null, username = 'Zhang San', password='123', age=23, sex =' male '}

7. Solve the problem of garbled code

In Tomcat8, the code of GET request is UTF-8 by default

In order to solve the problem of garbled code in POST request, it is necessary to Register characterencoding filter in XML file

The coding filter must be configured before other filters, otherwise it will be invalid

<!-- to configure springMVC Coding filter for -->

5, Domain objects share data

(1) Request domain object

1. Using servlet API

public String testRequestByServletAPI(HttpServletRequest request) {
    request.setAttribute("testRequestScope", "Hello ServletAPI");
    return "success";

2. Using ModelAndView

public ModelAndView testModelAndView() {
    ModelAndView mav = new ModelAndView();
    //shared data 
    mav.addObject("testRequestScope", "Hello ModelAndView");
    //Set the view to realize page Jump
    return mav;

3. Using Model

public String testModel(Model model) {
    model.addAttribute("testRequestScope", "Hello Model");
    return "success";

4. Using Map

public String testMap(Map<String, Object> map) {
    map.put("testRequestScope", "Hello Map");
    return "success";

5. Using ModelMap

public String testModelMap(ModelMap modelMap) {
    modelMap.addAttribute("testRequestScope", "Hello ModelMap");
    return "success";

6. Supplement

  1. The return values of the above five data sharing methods are finally encapsulated into ModelAndView objects by DispatcherServlet
  2. Relationship between Model, ModelMap and Map

(2) Session domain object

public String testSession(HttpSession session) {
    session.setAttribute("testSessionScope", "Hello Session");
    return "success";

(3) Application domain object

public String testApplication(HttpSession session) {
    ServletContext application = session.getServletContext();
    application.setAttribute("testApplicationScope", "Hello Application");
    return "success";

6, View

Function of view: render data and display the data in the Model to users

The view in spring MVC is the view view

(1) ThymeleafView

When the view name set by the controller method does not have any prefix, it will eventually be processed as ThymeleafView and forwarded

DispatcherServlet --> processDispatchResult
					 --> render 
						--> resolveViewName

(2) Forwarding view

The default forwarding view in spring MVC: InternalResourceView

When the view name set by the controller method is prefixed with "forward:", the InternalResourceView view is created. At this time, the view name will not be resolved, but the prefix will be removed, and the rest will be used as the final path to jump through forwarding

(3) Redirect view

The default redirection view in spring MVC: RedirectView

When the view name set in the controller is prefixed with "redirect:", a RedirectView is created. At this time, the view name will not be resolved, but the prefix will be removed, and the rest will be used as the final path to jump through redirection. If the rest starts with /, the context path will be spliced automatically

(4) View controller

When the controller method is only used to realize page Jump, the following settings can be made

	path: Set the address of the request to be processed
	view-name: Set the view name corresponding to the request address
<mvc:view-controller path="/" view-name="index"/>


When the above settings exist, all request mappings in other controllers will be invalidated

At this point, you need to set the mvc annotation driver in the spring mvc core configuration file


7, RESTful

(1) Introduction

REST: Representational State Transfer, resource state transfer of presentation layer

(2) Realize

Through the four requests in the HTTP protocol: GET, POST, PUT and DELETE

They correspond to four basic operations: GET - GET resources, POST - create resources, PUT - update resources, DELETE - DELETE resources

operation Traditional way REST style
query getUserById?id=1 user/1,GET
preservation saveUser user,POST
delete deleteUser?id=1 user/1,DELETE
to update updateUser user,PUT

(3) HiddenHTTPMethodFilter

The HiddenHttpMethodFilter filter allows you to convert POST requests into DELETE requests or PUT requests

Conversion conditions:

​ ❶ the request mode of the current request must be post

​ ❷ set the parameter _method (= put/delete) in the request

On the web Register in XML file


(4) Delete case

Idea: hyperlink controls the form by binding click events

<a @click="deleteEmployee" th:href="@{|/employee/${employee.id}|}">delete</a>

<form id="deleteForm" method="post">
    <input type="hidden" name="_method" value="delete">
<script type="text/javascript">
    var vue = new Vue({
        el: "#dataTable",
        methods: {
            deleteEmployee: function (event) {
                var deleteForm = document.getElementById("deleteForm");
                deleteForm.action = event.target.href;
    			//Submit Form 
    			//Block the jump behavior of hyperlinks

8, HttpMessageConverter


Convert request message into Java object or Java object into response message

(1) @ RequestBody

@RequestBody can get the request body

You need to set a formal parameter in the controller method and use the annotation identification. The request body of the current request will automatically assign a value to the parameter

public String testRequestBody(@RequestBody String requestBody) {
    return "success";

(2) RequestEntity

RequestEntity is a type of encapsulated message

This type of formal parameter needs to be set in the formal parameter of the controller method, and the current request message will be assigned to this formal parameter

public String testRequestEntity(RequestEntity<String> requestEntity) {
    System.out.println("Request header = " + requestEntity.getHeaders());
    System.out.println("Request body = " + requestEntity.getBody());
    return "success";

(3) @ ResponseBody

@ResponseBody is used to identify a controller method

The return value of this method can be directly used as the response body of the response message to respond to the browser

public String testResponseBody() {
    return "success";

1. Processing json

❶ import dependency


❷ enable annotation drive

<mvc:annotation-driven />

❸ annotation identification controller

//If you return the java object directly, it will be automatically converted into a string in json format
public User testResponseUser() {
    return new User(1001, "admin", "123", 15, "male");

2. Dealing with ajax

❶ request hyperlink

<div id="app">
    <a th:href="@{/testAjax}" @click="testAjax">SpringMVC handle ajax</a>

❷ vue and axios handle click events

<script type="text/javascript">
    var vue = new Vue({
            testAjax:function (event) {
                }).then(function (response) {

❸ controller method

public String testAjax(String username, String password) {
    System.out.println("username = " + username);
    System.out.println("password = " + password);
    return "Hello Ajax";

(4) @ RestController

@The RestController annotation is a composite annotation that can be used in the controller

Function: it is equivalent to adding @ Controller annotation to the Controller and @ ResponseBod annotation to all methods therein

(5) ResponseEntity

It is used for the return value type of the controller method. The return value of this method is the response message to the browser

1. File download

public ResponseEntity<byte[]> testDown(HttpSession session) throws IOException {
    //Get ServletContext object
    ServletContext servletContext = session.getServletContext();
    //Get the real path of the file in the server
    String realPath = servletContext.getRealPath("/static/img/1.png");
    //Create input stream
    FileInputStream is = new FileInputStream(realPath);
    //Create byte array
    byte[] bytes = new byte[is.available()];
    //Read data into byte array
    //Create an HttpHeader object and set the response header information
    MultiValueMap<String, String> headers = new HttpHeaders();
    //Set download method and file name
    headers.add("Content-Disposition", "attachment;filename=1.png");
    //Set response status code
    HttpStatus statusCode = HttpStatus.OK;
    //Create ResponseEntity object
    ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
    return responseEntity;

2. File upload

❶ add dependency


❷ register file parser

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

❸ page form

<form th:action="@{/testUp}" method="post" enctype="multipart/form-data">
    <input type="file" name="photo">
    <input type="submit" value="upload">

❹ controller method

public String testUp(MultipartFile photo, HttpSession session) throws IOException {
    //Get the uploaded file name
    String fileName = photo.getOriginalFilename();
    //Get file suffix
    String suffixName = fileName.substring(fileName.lastIndexOf("."));
    //Deal with file name duplication
    fileName = UUID.randomUUID().toString() + suffixName;
    //Get the path of the photo directory in the server
    ServletContext servletContext = session.getServletContext();
    String photoPath = servletContext.getRealPath("photo");
    File file = new File(photoPath);
    if (!file.exists()) {
    String finalPath = photoPath + File.separator + fileName;
    //Realize upload
    photo.transferTo(new File(finalPath));
    return "success";

9, Interceptor

Function: intercept the execution of the controller method

(1) Disposition

❶ create a class, implement the HandlerInterceptor interface, and rewrite three methods

❷ configure in spring MVC configuration file

    <!-- yes DispatcherServlet Intercept all requests processed -->
    <ref bean="firstInterceptor"/>
    <bean class="com.atguigu.mvc.interceptors.FirstInterceptor"/>
 		mvc:mapping  Set the request to be intercepted
		mvc:exclude-mapping  Set requests that do not need to be intercepted
        <mvc:mapping path="/**"/>
        <mvc:exclude-mapping path="/"/>
        <ref bean="firstInterceptor"/>

(2) Three abstract methods


​ Execution time: before controller execution

​ Description: return true and release; Return false to intercept


​ Execution time: after the controller executes


​ Execution time: after rendering the view

(3) Execution sequence

❶ if the preHandle of each interceptor returns true

​ preHandle: execute in the order of configuration

​ postHandler: execute in reverse order of configuration order

​ After completion: execute in reverse order of configuration order

❷ if the preHandle of an interceptor (A) returns false

​ preHandler: before interceptor A, including A, it will be executed

​ postHandler: none will be executed

​ After completion: before interceptor A, it will be executed without A

10, Exception handler

Spring MVC provides an interface to handle exceptions that occur during the execution of controller methods: HandlerExceptionResolver

The implementation classes of HandlerExceptionrResolver interface include DefaultHandlerExceptionResolver and SimpleMappingExceptionResolver

Spring MVC provides a custom exception handler, SimpleMappingExceptionResolver

(1) Configuration based

<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
                property The key represents the exception handled
                property The value of represents the name of the view to jump to when an exception occurs
            <prop key="java.lang.ArithmeticException">error</prop>
    <!-- Share exception information in the request domain -->
    <property name="exceptionAttribute" value="ex"/>

(2) Annotation based

public class ExceptionController {

    @ExceptionHandler(value = {ArithmeticException.class, NullPointerException.class})
    public String testException(Exception exception, Model model) {
        model.addAttribute("ex", exception);
        return "error";

11, Full annotation configuration

Use configuration classes and annotations instead of web Functions of XML and spring MVC configuration files

(1) Replace web xml

public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {

    //Specifies the configuration class of spring
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringConfig.class};

    //Specifies the configuration class of spring MVC
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{WebConfig.class};

    //Specify the mapping rule of DispatcherServlet, i.e. URL pattern
    protected String[] getServletMappings() {
        return new String[]{"/"};

    //Add filter
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();
        return new Filter[]{characterEncodingFilter, hiddenHttpMethodFilter};

(2) Replace MVC profile

 * Replace the configuration file of spring MVC
 * 1,Scan component 2, view parser 3, view controller 4, default servlet handler
 * 5,mvc Annotation driver 6. File upload parser 7. Exception handling 8. Interceptor
//1. Scan component
//5. mvc annotation driven
public class WebConfig implements WebMvcConfigurer {

    public void addViewControllers(ViewControllerRegistry registry) {

    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {

    //6. File upload parser
    public CommonsMultipartResolver multipartResolver() {
        return new CommonsMultipartResolver();

    //7. Exception handling
    public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
        SimpleMappingExceptionResolver exceptionResolver = new SimpleMappingExceptionResolver();
        Properties prop = new Properties();
        prop.setProperty("java.lang.ArithmeticException", "error");

    //8. Interceptor
    public void addInterceptors(InterceptorRegistry registry) {
        FirstInterceptor firstInterceptor = new FirstInterceptor();

    //2. View parser
    //2.1. Configure and generate template parser
    public ITemplateResolver templateResolver() {
        WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(webApplicationContext.getServletContext());
        return templateResolver;
    //2.2. Generate a template engine and introduce a template parser into the template engine
    public SpringTemplateEngine templateEngine(ITemplateResolver templateResolver) {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        return templateEngine;
    //3. Generate the parser template and inject it into the parser engine
    public ViewResolver viewResolver(SpringTemplateEngine templateEngine) {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        return viewResolver;

12, MVC execution process

(1) Common components

  • Front end controller (provided by dispatcher)

    Function: handle requests and responses in a unified way. It is the center of the whole process control, and it calls other components to handle user requests

  • HandlerMapping: processor mapper (provided by the framework)

    Function: find the Handler according to the requested url, method and other information

  • Handler: processor

    Function: process specific user requests under the control of dispatcher servlet

  • HandlerAdapter: processor adapter (provided by the framework)

    Function: execute the processor (controller method)

  • ViewResolver: View resolver (provided by the framework)

    Function: analyze the view to get the corresponding view, such as ThymeleafView, InternalResourceView


  • View: View

    Function: display the model data to users through the page

(2) Execution process

Posted by scbookz on Tue, 24 May 2022 18:20:00 +0300