0

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?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Using BigDecimal makes sense but I do not need to check the value range of my parameters. I just need to check whether they are numeric or not.
If num1 is not numeric, spring will not be able to bind the parameter and either would throw a ServletRequestBindingException or just will not find a proper endpoint to handle the request.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.