How Spring Boot uses @RequestParam for data validation

How Spring Boot uses @RequestParam for data validation

In web applications, user-submitted data is usually passed in the form of request parameters. In Spring Boot, @RequestParamannotations to obtain request parameters. But how do you ensure the validity of these request parameters? In this article, we will introduce how to use @RequestParamannotations for data validation, and provide some sample codes to help you better understand.

insert image description here

Introduction to @RequestParam

In Spring Boot, @RequestParamannotations are used to get parameter values ​​from the request. By default, parameters are required, and MissingServletRequestParameterExceptionan exception . However, you can use requiredthe attribute to make a parameter optional.

For example, the following code uses @RequestParamannotations to obtain ida request parameter named :

@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id, @RequestParam Long status) {
    // 处理获取用户逻辑
}

In the code above, @RequestParamthe annotation is used to get the request parameter statusnamed . An exception is thrown if the request does not include statusthe parameter MissingServletRequestParameterException.

Data validation

To ensure the validity of the request parameters, you can use the annotations in javax.validation.constraintsthe package to verify the request parameters. For example, the following code uses @Minannotations to validate idthe minimum value of the parameter:

@GetMapping("/users/{id}")
public User getUser(@PathVariable @Min(1) Long id) {
    // 处理获取用户逻辑
}

In the above code, @Minthe annotation is used to verify that the minimum value of idthe parameter is 1. If idthe argument is less than 1, MethodArgumentNotValidExceptionan exception will be thrown.

In addition to @Minannotations , there are many other annotations that can be used to validate request parameters. For example, @Maxannotations are used to verify the maximum value of a parameter, @NotBlankannotations are used to verify whether a string is not empty, @Emailannotations are used to verify the format of an email address, etc.

custom error message

By default, MethodArgumentNotValidExceptionan exception . However, you can use messagethe attribute to specify a custom error message.

For example, the following code uses a custom error message to validate the minimum value of idthe parameter :

@GetMapping("/users/{id}")
public User getUser(@PathVariable @Min(value = 1, message = "id 必须大于等于 1") Long id) {
    // 处理获取用户逻辑
}

In the code above, we use messagethe attribute to specify a custom error message. If idthe argument is less than 1, MethodArgumentNotValidExceptionan exception will be thrown with a custom error message.

Combined check

Sometimes, you may need to perform combined validation on multiple request parameters. For example, you might need to verify that startthe parameter is less than endthe parameter. In this case, you can use @Validannotations and custom objects to implement combined validation.

Here is a sample code that uses a custom object DateRangeto combine the checksum startand endparameters :

public class DateRange {
    @NotNull
    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
    private LocalDate start;

    @NotNull
    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
    private LocalDate end;

    // getters/setters omitted
}

@GetMapping("/users")
public List<User> getUsers(@Valid DateRange dateRange) {
    // 处理获取用户列表逻辑
}

In the code above, we use @Validannotations to validate DateRangethe object. DateRangeThe object contains startand endproperties, @NotNullwhich @DateTimeFormatare validated using the and annotations, respectively. If startgreater than end, MethodArgumentNotValidExceptionan exception .

Summarize

In this article, we introduced how to use @RequestParamannotations to obtain request parameters, and use javax.validation.constraintsannotations in the package to verify request parameters. We also show how to increase the flexibility of data validation by using custom error messages and combined validations. Through these sample codes, you can better understand how to use @RequestParamfor .

Here is the complete sample code:

@RestController
public class UserController {
    @GetMapping("/users/{id}")
    public User getUser(@PathVariable @Min(value = 1, message = "id 必须大于等于 1") Long id) {
        // 处理获取用户逻辑
    }

    public class DateRange {
        @NotNull
        @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
        private LocalDate start;

        @NotNull
        @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
        private LocalDate end;

        // getters/setters omitted
    }

    @GetMapping("/users")
    public List<User> getUsers(@Valid DateRange dateRange) {
        // 处理获取用户列表逻辑
    }
}

Hope this article is helpful to you, thanks for reading!

Guess you like

Origin blog.csdn.net/2302_77835532/article/details/131341713