简体   繁体   中英

Spring Boot validating request parameters

I am trying to learn Spring Boot and working on a simple REST API which I develop a simple calculator.

I have a service class annotated with @Service and it has a simple method

public double calculate(String operation, double num1, double num2) {
        ...
}

And I am calling this method from the controller like

@GetMapping("/calculate")
public double calculate(@RequestParam(value = "op") String op,
                        @RequestParam(value = "num1") double num1,
                        @RequestParam(value = "num2") double num2) {

    return calculatorService.calculate(op, num1, num2);
}

I want to validate these parameters(Whether num1 and num2 are numeric and all parameters should be not null). What is the best practice to validate the request parameters for Spring Boot?

It depends on what validation you want to perform.

One way would be to use validation annotations on the parameters themselves.

For example, @NotNull , @Min , @Max , etc. These particular ones can be found in javax.validation:validation-api , but there are many others (and you can build your own).

@GetMapping("/calculate")
public double calculate(@RequestParam(value = "op") @NotNull String op,
                        @RequestParam(value = "num1") double num1,
                        @RequestParam(value = "num2") double num2) {

The @NotNull validation will ensure that op is not null - you might want to use a @NotEmpty or @NotBlank annotation to ensure that the actual value of op has a length > 0 or a trimmed length > 0 respectively.

As Cristian Colorado points out in their comment below, Spring will automatically fail validation (or endpoint matching) if either num1 or num2 are not valid double values.

As you have told that you want to validate only Number @NumberFormat Annotation is there. The @NumberFormat annotation applies to subclasses of java.lang.Number (Integer, Float, Double, BigDecimal, etc.)

@NumberFormat(style=Style.NUMBER)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM