简体   繁体   English

Spring Boot验证请求参数

[英]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. 我正在尝试学习Spring Boot并致力于开发一个简单的计算器的简单REST API。

I have a service class annotated with @Service and it has a simple method 我有一个用@Service注释的服务类,它有一个简单的方法

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). 我想验证这些参数(num1和num2是否为数字,并且所有参数都不应该为null)。 What is the best practice to validate the request parameters for Spring Boot? 验证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). 例如, @NotNull@Min@Max等,这些特别的人可以在发现javax.validation:validation-api ,但也有许多人(你可以建立自己的)。

@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. @NotNull验证将确保op不为空-您可能要使用@NotEmpty@NotBlank批注以确保op的实际值的长度分别为> 0或修剪长度> 0。

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. 正如Cristian Colorado在下面的评论中指出的那样,如果num1num2都不是有效的double值,则Spring将自动通过验证(或端点匹配)。

As you have told that you want to validate only Number @NumberFormat Annotation is there. 如您所知 ,您只想验证Number @NumberFormat批注。 The @NumberFormat annotation applies to subclasses of java.lang.Number (Integer, Float, Double, BigDecimal, etc.) @NumberFormat批注适用于java.lang.Number的子类(整数,浮点数,双精度,BigDecimal等)

@NumberFormat(style=Style.NUMBER)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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