Deciphering SpringMVC: Exploring common annotations, let your Java application set sail quickly!

What is Spring MVC?

Spring MVC is a module in the Spring framework and a Java-based web application development framework. It provides a way to build flexible, efficient, and scalable web applications. Spring MVC allows developers to separate business logic from view logic, and supports the MVC (Model-View-Controller) design pattern, making the development process more modular and easier to manage.
In Spring MVC, the controller (Controller) is responsible for processing user requests, the model (Model) represents the data and business logic of the application, and the view (View) is used to display data to the user. The request is first received by the DispatcherServlet (front-end controller), then finds the corresponding Controller for processing according to the configured HandlerMapping, and finally returns the corresponding view .

Common Notes

@RequestMapping

@RequestMapping is one of the most commonly used annotations in Spring Web applications, and it is used to implement URL routing mapping.

Route mapping means that when a user visits a url, the process of mapping the user's request to a method of a class in the program is called route mapping

@Controller
//标记类为控制器,处理用户请求
@ResponseBody
//将方法返回的对象直接作为响应体返回给客户端
@RequestMapping("/user")
public class UserDemo {
    
    
@RequestMapping(value = "/hi")
public  Object getHi(){
    
    
    return "zcx,你好!";
}
}

We can use http://localhost:8080/user/hi to access, that is, localhost:8080 plus @RequestMapping("/user") on the class and @RequestMapping(value = "/hi") on the method
insert image description here
@RequestMapping can modify both classes and methods.

@Controller
//标记类为控制器,处理用户请求
@ResponseBody
//将方法返回的对象直接作为响应体返回给客户端
public class UserDemo {
    
    
    @RequestMapping(value = "/hi")
public  Object getHi(){
    
    
    return "zcx,你好!";
}

Using http://localhost:8080/hi to access the result is the same.

The @RequestMapping annotation can be used to process GET requests, POST requests, and other HTTP method requests in Spring MVC

Of course, if you specify the request, you can also write the following
two ways of writing the GET request:


@RequestMapping(value = "/user",method = RequestMethod.GET)
@GetMapping("/user")

Two ways of writing POST requests:

@RequestMapping(value = "/user",method = RequestMethod.POST)
@PostMapping("/user")

@RequestParam

It is used to bind request parameters to method parameters, which can be used to solve the problem of inconsistency between front-end and back-end parameter names.

@Controller
//标记类为控制器,处理用户请求
@ResponseBody
//将方法返回的对象直接作为响应体返回给客户端
@RequestMapping("/user")
public class UserDemo {
    
    
    @RequestMapping(value = "/hi")
public  Object getHi(@RequestParam("n") String name){
    
    
        System.out.println(name+"你好");
    return name+"你好!";
}
}

We directly use postman to request access and
insert image description here
bind key-n to the parameters in the method. Of course, if we use name again, an error will be reported (this is because the backend has declared that the frontend must pass a parameter of n).

The @RequestParam annotation also supports other attributes, such as:
required: Specifies whether the parameter is required, and the default is true.
defaultValue: Set the default value of the parameter.

public  Object getHi(@RequestParam(value = "n",required = false) String name)
public  Object getHi(@RequestParam(value = "n",defaultValue = "zcx") String name)

@RequestBody

@RequestBody is an annotation in the Spring MVC framework, which is used to receive the data in the HTTP request body and bind it to the parameters of the method. Typically used to process data passed in a POST or PUT request, especially in JSON or XML format.

Suppose we have a simple entity class User representing user information:

public class User {
    
    
    private String username;
    private String email;
    // Getters and setters
}

Now, we want to create a new user through a POST request, and pass the user information to the backend in JSON format. We can use the @RequestBody annotation to convert the JSON data in the request body into a User object

@RestController
public class UserController {
    
    

    @PostMapping("/createUser")
    public String createUser(@RequestBody User user) {
    
    
        // 处理逻辑,user对象将会从请求体中获取JSON数据
        return "User created successfully!";
    }
}

When the client sends a POST request with the following JSON data:

{
    
    
  "username": "john_doe",
  "email": "[email protected]"
}

The @RequestBody annotation converts the JSON data in the request body into a User object, where the value of the username field is "john_doe" and the value of the email field is "[email protected]". Then, the parameter user in the createUser method will be automatically populated as a User object containing the above JSON data.

@PathVariable

Used to get the value of the parameter from the URL path of the request. It is typically used to handle RESTful requests, extracting path variables from URLs and binding them to method parameters.

@GetMapping("/example/{id}")
    public String handleGetRequest(@PathVariable("id") Long id) {
    
    
        // 处理逻辑,id 是从 URL 路径中获取的参数值
        System.out.println("id="+id);
        return "viewName";
    }

Use http://localhost:8080/user/example/99 to visit,
insert image description here
you can see that the obtained id is 99
insert image description here

The @PathVariable annotation also supports other attributes, such as:
required: Specifies whether the path variable is required, and the default is true.

@RequestPart

The @RequestPart annotation is used to handle complex request data, especially multipart (multipart) request data, which is usually used in file upload scenarios. It can be used to get files and other data from requests.

@RequestMapping("file")
    public String FileUpload(String name,@RequestPart("file") MultipartFile file) throws IOException {
    
    
        String fileName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
      // ⽂件保存地址
        String filePath = ClassUtils.getDefaultClassLoader().getResource("stat ic").getPath() +
                "/" + UUID.randomUUID() + fileName;
      // 保存⽂件
        file.transferTo(new File(filePath));
        return "上传成功!"+filePath;
    }

insert image description here
The @RequestPart annotation will correctly map the data in the request to the name object and the file object, and then we can perform corresponding business logic processing on the backend.

Guess you like

Origin blog.csdn.net/st200112266/article/details/132114891