Detailed explanation and specific examples of @RequestParam, @RequestBody, @RequestAttribute, @RequestPart and @PathVariable

Table of contents

1. @RequestParam

conventional usage

@PathVariable annotation

optional parameters

2. @RequestBody

conventional usage

JSON format data

3. @RequestAttribute

4. @RequestPart

conventional usage

upload multiple files

Summarize:


When using the Spring Web framework to develop Web applications, we usually need to obtain information such as request parameters, request body, and request attributes. In order to easily extract this information, Spring Web provides multiple annotations, including @RequestParam, @RequestBody, @RequestAttributeand@RequestPart etc.

In this blog, we will introduce the use of these annotations and provide concrete examples.

1. @RequestParam

The @RequestParam annotation is used to obtain the value of an HTTP request parameter.

Attributes such as name, value, required, and defaultValue can be used to specify information such as the parameter name, whether it is required, and the default value. If the request parameter name is inconsistent with the method parameter name, it can be solved by setting the value attribute of @RequestParam.

The sample code is as follows:

conventional usage

@Controller
@RequestMapping("/user")
public class UserController {
    @GetMapping("/info")
    public String userInfo(@RequestParam("user_id") int userId) {
        //处理业务逻辑
        return "user_info";
    }
}

In the above code, the @RequestParam annotation obtains the value of the parameter named user_id submitted by the front-end page, and assigns it to the method parameter userId.

@PathVariableannotation

valueAttributes can be omitted if the request parameter and method parameter have the same name .

@GetMapping("/users/{id}")
public User getUserById(@PathVariable Long id, @RequestParam String name) {
    return userService.getUserByIdAndName(id, name);
}

In this example, we use @PathVariableannotations to idmap URL path parameters to method parameters id, and use annotations to map @RequestParamrequest parameters to method parameters .namename

optional parameters

Sometimes, request parameters may not be necessary. To avoid throwing an exception, we can set requiredthe property to false.

@GetMapping("/users")
public List<User> getUsers(@RequestParam(required = false) String name) {
    if (name == null) {
        return userService.getAllUsers();
    } else {
        return userService.getUsersByName(name);
    }
}

In this example, we use @RequestParamannotations to namemap request parameters to method parameters nameand set requiredthe property to false. If the request parameter does not exist, returns all users; otherwise returns a list of users with the specified name.

2. @RequestBody

The @RequestBody annotation is used to obtain the content in the request body of the HTTP request, and is often used to process POST requests.

After using this annotation, Spring will automatically encapsulate the data such as JSON/XML in the request body into Java objects for easy operation.

The sample code is as follows:

conventional usage

@Controller
@RequestMapping("/user")
public class UserController {
    @PostMapping("/add")
    public String addUser(@RequestBody User user) {
        //处理业务逻辑
        return "add_success";
    }
}

In the above code, the @RequestBody annotation encapsulates the JSON/XML data in the request body into a User object to facilitate subsequent operations.

JSON format data

If the request body is data in JSON format, we can use @RestControllerannotations and @PostMappingannotations to automatically convert it to a Java object.

@RestController
public class UserController {
    @PostMapping("/users")
    public User createUser(@RequestBody CreateUserRequest request) {
        User user = new User(request.getName(), request.getAge());
        return userService.createUser(user);
    }
}

public class CreateUserRequest {
    private String name;
    private int age;
    // getters and setters
}

In this example, we use @RestControllerannotations and @PostMappingannotations to handle POST requests, and use CreateUserRequestclasses to automatically convert the request body to a Java object.

3. @RequestAttribute

The @RequestAttribute annotation is used to obtain the attribute value in the HTTP request, usually set by a filter or interceptor before the request is processed.

The attribute name can be specified through the name attribute. The sample code is as follows:

@Controller
@RequestMapping("/user")
public class UserController {
    @GetMapping("/info")
    public String userInfo(@RequestAttribute("user_name") String userName) {
        //处理业务逻辑
        return "user_info";
    }
}

In the above code, the @RequestAttribute annotation obtains the attribute value named user_name in the request and assigns it to the method parameter userName.

4. @RequestPart

The @RequestPart annotation is used to process file upload requests, and can directly encapsulate files into Java objects.

When processing file uploads, you need to use the multipart/form-data encoding method, and the name value in the form needs to be consistent with the value value in the @RequestPart annotation. The sample code is as follows:

conventional usage

@Controller
@RequestMapping("/user")
public class UserController {
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<String> uploadFile(@RequestPart MultipartFile file, @RequestParam String description) {
    // 处理文件和参数
}
}

In this example, we use @RequestPartannotations to map uploaded files to method parameters file, and @RequestParamannotations to map request parameters descriptionto method parameters description. This way, we can upload the file with description information.

upload multiple files

If you want to upload multiple files, you can use MultipartFile[]the type parameter.

@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> uploadFiles(@RequestPart("fileList") MultipartFile[] fileList, @RequestParam String description) {
    // 处理文件和参数
}

In this example, we use @RequestPartannotations to map multiple uploaded files to method parameters fileList. In this way, we can upload multiple files with description information.

Note: @RequestPartWhen using annotations, it must be specified at the same time Content-Type, multipart/form-dataotherwise an exception will be thrown.

Summarize:

The above is the detailed explanation and specific examples of @RequestParam, @RequestBody, @RequestAttribute, @RequestPart annotations. They can greatly simplify the acquisition of HTTP request parameters and the operation of file upload.

Guess you like

Origin blog.csdn.net/qq_63029994/article/details/130401888