简体   繁体   English

Spring boot2 路径变量验证

[英]Spring boot2 path variable validation

I am using spring boot for creating rest services.我正在使用 spring 引导来创建 rest 服务。 I need to validate the parameter passed.我需要验证传递的参数。 I have a service like below,我有如下服务,

@GetMapping(value="/employee/{Id}")
public EmployeeDTO getEmployeeDetails(@PathVariable String Id) {
    ...
}

I need to throw error if Id is not passed in url.如果 Id 未在 url 中传递,我需要抛出错误。 Like "Missing Id in request".就像“请求中缺少 ID”。 I was able to achieve using below,我能够在下面使用,

@GetMapping(value={"/employee", "/employee/{Id}"})
public EmployeeDTO getEmployeeDetails(@PathVariable String Id) {
    ...
}

And handled MissingPathVariableException in ExceptionHandler annotated with @ControllerAdvise.并在使用 @ControllerAdvise 注释的 ExceptionHandler 中处理 MissingPathVariableException。

But I wanted to know is this the right way to check?但我想知道这是检查的正确方法吗?

You can use @ControllerAdvise to handle exceptions that are generated while executing your actual code.您可以使用@ControllerAdvise处理在执行实际代码时生成的异常。

For Path variable validation, you can make use of spring-boot-starter-validation .对于路径变量验证,您可以使用spring-boot-starter-validation

Add this maven dependency:添加此 maven 依赖项:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Then your controller will look like:然后您的 controller 将如下所示:

@GetMapping(value={"/employee", "/employee/{Id}"})
public EmployeeDTO getEmployeeDetails(
    @NotBlank(message = "Missing Id in request")
    @PathVariable String Id) {
    ...
}

I recommend you to read this: Validating Form Input我建议您阅读以下内容: 验证表单输入

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

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