Spring验证相关请求参数

标签 spring spring-mvc spring-boot

@RequestMapping(value = "/test")
@ResponseBody
public Object test(@RequestParam("latitude") String latitude, 
                   @RequestParam("longitude") String longitude) {
}

在这种情况下,如果纬度不为空,则经度也必须不为空。

如何验证相关请求参数? 是否有开箱即用的解决方案,或者手动验证?

最佳答案

如果您使用的是最新版本的 spring,则有一个注释 @Validated .

通过此注释,我们可以验证 @RequestParam@PathVariable

最需要注意的是@Valid用于验证 RequestBody抛出异常 MethodArgumentNotValidException

@Validated抛出 ConstraintViolationException

由于这两个异常属于不同类型,因此您必须使用 @ExceptionHandler 以不同方式处理它们。 ,如下所示:-

@ExceptionHandler(value = { ConstraintViolationException.class })
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public ResponseEntity<Type> handleConstraintViolationException(ConstraintViolationException e) {
    // your code here to handle the exceptions accordingly 
}

@ExceptionHandler(value = { MethodArgumentNotValidException.class })
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public ResponseEntity<Type> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
    // your code here to handle the exceptions accordingly 
}

关于Spring验证相关请求参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49574181/

相关文章:

java - Spring Rest Controller 的模拟主体

java - 收到SIGTERM后如何正确关闭Spring bean?

spring - 用另一个上下文中的模拟版本替换一个上下文中的 spring bean

java - th :disabled objects in Thymeleaf

java - Spring Boot 默认测试抛出 IllegalStateException

java - 内容类型不支持 java Spring

java - Spring + Hibernate 不会自动打开 session

java - 访问已编译的 jar/war 文件之外的文件

java - 后端服务器轮询其他 API 的 Web 应用程序的架构模式。

java - RequestMappings 根本不起作用