2. Why use the SpringMVC framework

In native Java EE technology, Servlet components handle user requests. Typically, each Servlet component handles one request. For example, a “user registration” request might be handled by a UserRegServlet. The “user login” request might be handled by the UserLoginServlet… In more complex business systems, the variety of requests submitted by users can be very large, resulting in a large number of Servlet components! This makes it difficult to manage the code, and many Servlet components take up a lot of memory when the project is running…

In the design of the SpringMVC framework, this problem is solved by reducing the number of Servlet components by using a component of a DispatcherServlet that receives all requests (but can also be configured for specific requests, such as only *.do requests)!

Originally Servlet is used for processing requests, but in the SpringMVC framework, the main role of DispatcherServlet is to receive a request, distributed to the specific processing request Controller component, it does not process the request itself! Each Controller component in SpringMVC can have several ways to handle requests, that is, each Controller component can handle several requests, so even if the project is complex and there are many types of requests, the number of Controller components is not very large!

The relationship between DispatcherServlet and Controller is like the relationship between the number machine in the bank lobby and the business desk.

The SpringMVC framework is simpler to use than native Java EE!


1. Display the page

Add thymeleaf and Thymeleaf-spring5 dependencies to the project’s pom.xml:

<! -- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf -->
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf</artifactId>
    <version>3.0.11. RELEASE</version>
</dependency>
<! -- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf-spring5 -->
<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId>thymeleaf-spring5</artifactId>
    <version>3.0.11. RELEASE</version>
</dependency>
Copy the code

Note: The samegroupIdNext, eachartifactIdDifferent, but ifversionThe numbering rules are the same and need to be used differently within the same projectartifactIdThe corresponding dependencies must be the sameversion!

package cn.tedu.spring;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;

@ComponentScan("cn.tedu.spring")
public class SpringMvcConfigurer implements WebMvcConfigurer {

	private String characterEncoding = "utf-8";
	
	@Bean
	public ViewResolver configViewResolver(a) {
		ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
		templateResolver.setCharacterEncoding(characterEncoding);
		templateResolver.setTemplateMode("HTML");
		templateResolver.setCacheable(false);
		templateResolver.setPrefix("/templates/");
		templateResolver.setSuffix(".html");
		
		SpringTemplateEngine templateEngine = new SpringTemplateEngine();
		templateEngine.setTemplateResolver(templateResolver);
		
		ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
		viewResolver.setCharacterEncoding(characterEncoding);
		viewResolver.setTemplateEngine(templateEngine);
		returnviewResolver; }}Copy the code

2. Receive the request parameters submitted by the client

2.1. Receive request parameters using HttpServletRequest

Add parameters of type HttpServletRequest to the parameter list of the methods used to process the request. During processing, the request parameters can be obtained by calling the getParameter() method of the parameter object:

@RequestMapping("handle_reg.do")
@ResponseBody
public String handleReg(HttpServletRequest request) {
    System.out.println("HelloController.handleReg()");

    String username = request.getParameter("username");
    String password = request.getParameter("password");
    Integer age = Integer.valueOf(request.getParameter("age"));
    String phone = request.getParameter("phone");
    String email = request.getParameter("email");
    System.out.println("username=" + username);
    System.out.println("password=" + password);
    System.out.println("age=" + age);
    System.out.println("phone=" + phone);
    System.out.println("email=" + email);

    return "OK."; // We don't care how to respond, so we use @responseBody to return a string
}
Copy the code

2.2. Declare request parameters directly as parameters of the method that processes the request

Request parameters submitted by the client can be declared directly as parameters of the method that processes the request, for example:

@RequestMapping("handle_reg.do")
@ResponseBody
public String handleReg(String username, String password, Integer age, String phone, String email) {
    System.out.println("HelloController.handleReg()");

    System.out.println("[2] username=" + username);
    System.out.println("[2] password=" + password);
    System.out.println("[2] age=" + age);
    System.out.println("[2] phone=" + phone);
    System.out.println("[2] email=" + email);

    return "OK."; // We don't care how to respond, so we use @responseBody to return a string
}
Copy the code

When declaring parameters, ensure that the name of the request parameter submitted by the client is consistent with the name of the method used to process the request. If the parameter declared on the server side is not submitted when the client submits the request, the value of the parameter declared on the server side is null.

In the request method, you can declare parameters of the desired type. For example, in the above code, age is declared to be an Integer type, provided that the client ultimately submits data that can be converted to Integer. If the client submits data that cannot be converted at all, an error will be reported.

Although this is simple and convenient, it is not suitable for application scenarios with too many request parameters!

2.3. Receive request parameters using encapsulated parameter objects

You can encapsulate each request parameter to be submitted by the client into a custom data type, for example:

package cn.tedu.spring;

public class User {

	private String username;
	private String password;
	private Integer age;
	private String phone;
	private String email;
    
    // Getters & Setters
    // toString()
    
}
Copy the code

Then add the above custom data types to the parameter list of the method that handles the request:

@RequestMapping("handle_reg.do")
@ResponseBody
public String handleReg(User user) {
    System.out.println("HelloController.handleReg()");

    System.out.println(user);

    return "OK."; // We don't care how to respond, so we use @responseBody to return a string
}
Copy the code

2.4 summary

First, using HttpServletRequest to receive request parameters described in 2.1 is not recommended;

If the number of request parameters is small and fixed, the practice described in 2.2 should be preferred.

If the number of request parameters is large or there is a possibility of adjustment later, the practice described in 2.3 should be preferred.

In addition, the above 2.2 and 2.3 practices can coexist!

3. Forward data to the template page

When you need to forward data to the Thymeleaf template page, you should first add ModelMap parameters to the parameter list of the method that processes the request, and when you need to transform the data, call the addAttribute() method of the ModelMap parameter object to encapsulate the data:

@RequestMapping("handle_login.do")
public String handleLogin(String username, String password, ModelMap modelMap) {
    System.out.println("UserController.handleLogin()");
    System.out.println("username=" + username);
    System.out.println("password=" + password);

    // Assume that root/1234 is the correct user name/password
    // Determine the user name
    if ("root".equals(username)) {
        // If the user name is correct, check the password
        if ("1234".equals(password)) {
            // If the password is correct, the login succeeds
            return "OK";
        } else {
            // The password is incorrect
            String message = "Login failed! Wrong password!";
            modelMap.addAttribute("errorMessage", message);
            return "error"; }}else {
        // The username is incorrect
        String message = "Login failed! Wrong username!";
        modelMap.addAttribute("errorMessage", message);
        return "error"; }}Copy the code

Later, in the Thymeleaf template page, use the Thymeleaf expression to display the previously encapsulated data:

<! DOCTYPEhtml>
<html>
<head>
<meta charset="UTF-8">
<title>The operating error</title>
</head>
<body>
<h1>Operation error:<span th:text="${errorMessage}"></span></h1>
</body>
</html>
Copy the code