[Spring MVC] Spring MVC program development tutorial: details of common annotations and usage methods

foreword

 Spring MVC is a commonly used web framework that helps developers quickly build scalable web applications. In order to provide a better development experience and higher code efficiency, Spring MVC provides various annotations. These annotations can be used for controllers, request parameters, response types, form data validation, exception handling, and more. In this article, we will introduce the commonly used annotations and usage methods in Spring MVC. Understanding the role of these annotations can help us better understand the working principle of the Spring MVC framework and improve our development efficiency.
facial expression



1 Introduction to Spring MVC

What is MVC?
MVC is a software architecture pattern, which is divided into three parts: model (Model), view (View) and controller (Controller). Its main idea is to divide the application into three main parts: model (data and business logic), view (user interface) and controller (request processor) to achieve separation of concerns and loose coupling. With this layered architecture, applications can be better maintained and extended, and applications are easier to test and design.
MVC design pattern

What is Spring MVC?
Spring MVC is a Java-based web framework for building web applications. It is part of the Spring framework and is flexible, extensible, and powerfully configurable. Spring MVC separates the different layers of an application by using the MVC (Model-View-Controller) design pattern.
The model layer represents data or business logic, the view layer represents UI elements, and the controller layer acts as an intermediary between these two layers. This separation allows for better modularity and easier to maintain code. Spring MVC also provides rich features, such as form processing, file upload, security, internationalization and validation, which can be easily integrated into web applications. In general:

  1. Spring MVC is a web framework.
  2. Spring MVC is built on top of the Servlet API.

SpringMVC
How to learn Spring MVC?
For Spring MVC, mastering the following three functions is equivalent to mastering Spring MVC.

  • Connection function: connect the user (browser) with the Java program, that is, accessing an address can call our
    Spring program.
  • The function of obtaining parameters: The user will bring some parameters when accessing, and find a way to obtain the parameters in the program.
  • The function of outputting data: After executing the business logic, the result of program execution should be returned to the user.

2 Spring MVC creation and connection

2.1 Create a Spring MVC project

There is no unique way to create a Spring MVC project. Here, a Spring Boot-based method is used to quickly build a Spring MVC environment. That is, when creating a Spring Boot project, check the Spring Web module.
Create a Spring MVC project

2.2 @RequestMapping annotation

The @RequestMapping annotation is one of the most commonly used annotations in the Spring MVC framework, and it is used to register the route mapping of the interface.

Route mapping: The so-called route mapping refers to the process of mapping the user's request to a certain method of a certain class in the program when the user visits a url, which is called route mapping.

It can be used on class level as well as method level. At the class level, a base URL mapping can be set to define specific request paths at the method level. At the method level, you can define specific behaviors and method parameters for processing requests, etc.

@RequestMappingAnnotations have various parameter settings, such as:

  • value: Specify the request URL processed by this method, which can be a string array and supports placeholders.
  • method: Specify the request method processed by this method, such as GET, POST, etc.
  • params: Specifies the parameters and their values ​​that must be included to limit the conditions of the request.
  • headers: Specify the request headers and their values ​​that must be included to limit the conditions of the request.
  • consumes: Specifies the Content-Type of the request, which is used to limit the conditions of the request.
  • produces: Specifies the Content-Type of the response, which is used to limit the conditions of the response.

Through these parameter settings, we can more precisely control the mapping and processing of requests, thereby implementing different business logics.

2.2.1 Basic use of @RequestMapping

@RequestMapping can be used on both classes and methods. When the annotation is added to both, the access address is the class + method

Next, the function we implement is to access the address: http://localhost:8080/user/hi, which can print "Hello, Huang Xiaohuang~" information.

Create a UserController class to realize the interconnection between the user and the Spring program. The specific implementation code is as follows:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller // Spring 启动时加载
@ResponseBody // 返回非页面数据
@RequestMapping("/user") // 路由规则注册
public class UserController {
    
    
	// 路由规则注册
    @RequestMapping("/hi")
    public String sayHello() {
    
    
        return "Hello, 黄小黄~";
    }
}

Realize the result 01

2.2.2 GET request or POST request?

Here is the conclusion directly. By default, the @RequestMapping annotation can receive both GET requests and POST requests. If you need to specify the method of receiving requests, you need to specify the GET/POST method type for the method parameter.

Specify to receive POST requests

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller // Spring 启动时加载
@ResponseBody // 返回非页面数据
@RequestMapping("/user") // 路由规则注册
public class UserController {
    
    
    // 指定 POST
    @RequestMapping(value = "/showPost", method = RequestMethod.POST)
    public String showPost() {
    
    
        return "接收到了 POST 请求~";
    }
}

result 2

2.2.3 @GetMapping and @PostMapping

SpringMVC also provides @GetMapping and @PostMapping annotations, which correspond to the GET type and POST type of the received request respectively. The following code demonstrates specifying to receive a GET request:

// 指定 GET
@GetMapping("/showGet")
public String showGet() {
    
    
    return "接收到了 GET 请求~";
}

3 Get parameters

3.1 Passing a single parameter/multiple parameters

In Spring MVC, you can directly use the parameter list in the method to pass parameters. The sample code is as follows:

// 传递单个参数
@GetMapping("/method01")
public String method01(int num) {
    
    
    return "num: " + num;
} 

achieve result 3
It can be seen that the parameters are passed normally.
However, for basic data types, there are pitfalls! What if you forget to pass parameters?
Achieving result 4
As you can see, the server returns a 500 status code. How to solve it? We can pass parameters in the form of wrapper classes for all basic data types. The sample code is as follows:

// 传递单个参数
@GetMapping("/method02")
public String method02(Integer num) {
    
    
    return "num: " + num;
}

That way, if the frontend forgets to pass the parameter, it will just return null. The problem is very clear: it is caused by forgetting to pass the num value~
result 5

How to pass multiple parameters?
Just add parameters to the method parameter list. When there are multiple parameters, when the front-end and back-end perform parameter matching, the matching is performed by the name of the parameter, so the position of the parameter does not affect the result of obtaining the parameter at the back-end.

3.2 passing objects

In Spring MVC, the assignment of parameter passing can be automatically realized. For example, passing a Student object:

import lombok.Data;

@Data
public class Student {
    
    
    private String name;
    private String password;
}

Pass object code implementation:

// 传递对象
@GetMapping("/student")
public String showStudent(Student student) {
    
    
    String name = student.getName();
    String password = student.getPassword();
    return name + " : " + password;
}

result 6

3.3 Backend parameter renaming (@RequestParam parameter mapping)

In some special cases, the parameter key passed by the front end may be inconsistent with the key received by our back end. For example, the front end passes a name to the back end, and the back end also has the curName field to receive it. There will be a situation where the parameters cannot be received. If this happens, we can use it to @RequestParamrename the parameter values ​​of the front and back ends. The sample code is as follows:

// 参数映射
@GetMapping("/para")
public String showCurName(@RequestParam("name") String curName) {
    
    
    return "curName = " + curName;
}

At this time, even if the parameter passed from the front end is name, it can be mapped normally:
result 7

3.4 @RequestParam parameter must pass setting

In the above example, if a non-name value is passed, the following error will occur:
result 7
What is the reason? You can find the clue by looking at @RequestParamthe implementation details of the annotation:
implementation details
you can see that required is true by default, that is, a 400 error will be reported if this parameter is not passed.

To set non-required parameters,
you only need to set required=false in @RequestParam to avoid reporting errors if they are not passed:

// 参数映射
@GetMapping("/para")
public String showCurName(@RequestParam(value = "name", required = false) String curName) {
    
    
    return "curName = " + curName;
}

result 8

3.5 @RequestBody receives JSON object

// 传递 JSON
@PostMapping("/set-student")
public String setStudent(@RequestBody Student student) {
    
    
    System.out.println(student);
    return "Student Set Success.";
}

Use PostMan to construct JSON and pass it to the backend:
result 9

3.6 @PathVariable Get the parameters in the URL

Sometimes, parameters are not passed in the form of name=xxx&password=xxx.
For example: http://localhost:8080/user/login/Huang Xiaohuang/123123
Among them, Huang Xiaohuang represents the value of name, and 123123 represents the value of password. How do we get the parameters in this case? It can be implemented using @PathVariable, and the backend implements the code:

// 获取 URL 中的参数
@GetMapping("/login/{name}/{password}")
public String login(@PathVariable String name, @PathVariable String password) {
    
    
    return "name = " + name + "<br>" +
            "password = " + password + "<br>" +
            "Login Success.";
}

result 10

3.7 @RequestPart upload files

The @RequestPart annotation can be used to process multipart/form-data type requests, often used to upload files. This annotation can be combined with the @RequestBody annotation to pass files and other form data. For example:

@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) {
    
    
    // 处理文件上传的逻辑
    return "success";
}

Here @RequestParam("file") means to obtain the file named "file" from the request, and the uploaded file will be stored in the MultipartFile object. We can use methods of MultipartFile object to process uploaded files.

Case: upload a picture to a certain directory of the machine

// 上传文件Demo
@RequestMapping("/upFile")
public String upFile(@RequestParam("myFile") MultipartFile file) throws IOException {
    
    
    // 上传的路径根目录
    String path = "D:\\info\\";
    // 路径+【唯一文件名】
    path += UUID.randomUUID().toString().replace("-", "");
    // 路径+文件名+【后缀】
    path += file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
    // 保存文件
    file.transferTo(new File(path));
    return path + "上传成功!";
}

result 11

3.8 Get Cookie/Session/header

Traditionally get header/cookie

// 传统获取 header/cookie
@RequestMapping("/method04")
public String method04(HttpServletRequest req, HttpServletResponse resp) {
    
    
    String name = req.getParameter("name");
    // 获取所有 Cookie 信息
    Cookie[] cookies = req.getCookies();
    // 获取 header 信息
    String userAgent = req.getHeader("User-Agent");
    return name + " : " + userAgent;
}

@CookieValue get cookie

// @CookieValue 获取 Cookie
@RequestMapping("/cookie")
public String cookie(@CookieValue("name") String name) {
    
    
    return "cookie: " + name;
}

@RequestHeader Get the header

// @RequestHeader 获取 header
@RequestMapping("/header")
public String header(@RequestHeader("User-Agent") String userAgent) {
    
    
    return "User-Agent: " + userAgent;
}

Session can use HttpServletRequest, as shown in the following code:

@RequestMapping("/sess1")
public String sess1(HttpServletRequest req) {
    
    
    // 如果 session 不存在, 不会自动创建
    HttpSession session = req.getSession(false);
    String username = "默认值";
    if (session != null && session.getAttribute("username") != null) {
    
    
        username = (String) session.getAttribute("username");
    }
    return username;
}

Simple way to get Session

// 更简洁方式获取 Session
@RequestMapping("/sess2")
public String sess2(@SessionAttribute(value = "username", required = false) String username) {
    
    
    return username;
}

4 return data

4.1 Return to static page

Create a static page index.html
Static pages

Create a controller and implement the corresponding method:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/test")
public class TestController {
    
    
    // 返回静态页面
    @RequestMapping("/index")
    public Object index() {
    
    
        // 执行业务
        // 返回 View -> index.html
        return "/index.html";
    }
}

result 12

4.2 return text/html

 // 返回 test/html
 @RequestMapping("/method1")
 @ResponseBody
 public String method1() {
    
    
     return "<h1>Hello, world!</h1>";
 }

result 13

4.3 Return JSON object

In the example below, @ResponseBodythe annotation tells SpringMVC to convert the returned Map object into a JSON object and return it to the client as an HTTP response.

@RequestMapping("/method2")
@ResponseBody
public Map<String, String> method2() {
    
    
    Map<String, String> map = new HashMap<>();
    map.put("黄小黄", "111");
    map.put("蒲小七", "777");
    return map;
}

result 14

4.4 Request redirection and request forwarding

return can not only return a view, but also realize jump. There are two ways to jump:

  • forward is request forwarding;
  • redirect is request redirection.

The sample code is as follows:

// 请求重定向
@RequestMapping("/index1")
public String index1() {
    
    
    return "redirect:/index.html";
}
// 请求转发
@RequestMapping("/index2")
public String index2() {
    
    
    return "forward:/index.html";
}

What is the difference between request forwarding and request redirection?

  1. Request forwarding is done inside the server. The client browser only sends a request. After receiving the request, the server directly forwards the request to another resource for processing. This process is transparent to the browser; while request redirection The client sends two requests. After the first request is responded by the server, the server will tell the browser to turn to a new resource, and the browser will initiate the request again after receiving the response.

  2. For request forwarding, the address bar of the client browser will not change, and remains the original address; while request redirection will change the address bar to a new address.

  3. Request forwarding uses the forward method, which can only be implemented within the same web application ; request redirection uses the sendRedirect method, which can achieve cross-domain jumps.

  4. Request forwarding is performed inside the server, so data in the same request field can be shared , while request redirection is two completely independent requests, and data in the request field cannot be shared.

  5. Request redirection has the same effect as direct access to the new address, and there is no inaccessibility to the original external resources; request forwarding server-side forwarding may cause the original external resources to be inaccessible.

4.5 Combined annotations: @RestController

@RestController = @Controller + @ResponseBody

  • If the value returned by @ResponseBody is a character, it will be converted into text/html, and if it is an object, it will be converted into application/json and returned to the front end.
  • @ResponseBody can be used to decorate a method or a class, and the class means that all methods in the class will return html or json instead of a view.

More annotations : https://docs.spring.io/spring-framework/reference/web/webmvc/mvc-controller/ann-requestmapping.html


write at the end

This article is included in the JavaEE programming road点击订阅专栏 and is being updated continuously.
 The above is the whole content of this article! Creation is not easy, if you have any questions, welcome to private message, thank you for your support!

insert image description here

Guess you like

Origin blog.csdn.net/m0_60353039/article/details/131566413