SpringBoot 使用javax.validation入参校验
2021/6/19 22:27:08
本文主要是介绍SpringBoot 使用javax.validation入参校验,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
需求:
controller层的入参数据添加基本校验,简化手写校验的代码逻辑
思路:
1. 使用javax.validation提供的参数校验(引入spring-boot-starter-validation)
2.手写处理方法ControllerExceptionHandler,用来捕获全局异常和校验异常中的BindingResult
最终代码
项目目录
maven
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.6</version> <relativePath/> </parent> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.10</version> </dependency> </dependencies> </project>
yaml
server: port: 9088 spring: application: name: demo
ControllerExceptionHandler
package com.example.demo.config; import com.example.demo.utils.RestResponse; import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpStatus; import org.springframework.validation.BindingResult; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import lombok.extern.slf4j.Slf4j; /** * @Author: yipeng * @Date: 2021/6/19 19:32 */ @Slf4j @ControllerAdvice public class ControllerExceptionHandler { @ResponseBody @ExceptionHandler(Exception.class) public RestResponse globalException(HttpServletRequest request, Exception ex) { log.error("controller system error path {} {}", request.getRequestURL(), ex.getMessage()); return RestResponse.build(HttpStatus.INTERNAL_SERVER_ERROR); } @ResponseBody @ExceptionHandler(MethodArgumentNotValidException.class) public RestResponse globalBindException(HttpServletRequest request, MethodArgumentNotValidException ex) { log.error("controller params is error path {} {}", request.getRequestURL(), ex.getMessage()); BindingResult bindingResult = ex.getBindingResult(); if (bindingResult.hasErrors()) { return RestResponse.build(HttpStatus.INTERNAL_SERVER_ERROR, bindingResult.getAllErrors().get(0).getDefaultMessage()); } return RestResponse.build(HttpStatus.INTERNAL_SERVER_ERROR); } }
VaildConroller
package com.example.demo.controller; import com.example.demo.utils.RestResponse; import com.example.demo.vo.VaildVo; import javax.validation.Valid; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import lombok.extern.slf4j.Slf4j; /** * @Author: yipeng * @Date: 2021/6/19 19:33 */ @Slf4j @RestController @RequestMapping("/vaild") public class VaildConroller { @PostMapping("/check") public RestResponse<String> trading(@RequestBody @Valid VaildVo vaildVo) { log.info(vaildVo.toString()); return RestResponse.buildSuccess(vaildVo.toString()); } }
RestResponse<T>
package com.example.demo.utils; import org.springframework.http.HttpStatus; import lombok.Data; import lombok.extern.slf4j.Slf4j; @Data @Slf4j public class RestResponse<T> { private int code; private String message; private T data; private RestResponse() { } public static RestResponse build(HttpStatus status) { RestResponse result = new RestResponse(); result.code = status.value(); result.message = status.getReasonPhrase(); return result; } public static <T> RestResponse<T> buildSuccess(T t) { RestResponse resp = build(HttpStatus.OK); resp.setData(t); return resp; } public static <T> RestResponse<T> build(HttpStatus status, String message) { RestResponse result = new RestResponse(); result.code = status.value(); result.message = message; result.setData(null); return result; } }
VaildVo
package com.example.demo.vo; import javax.validation.constraints.DecimalMax; import javax.validation.constraints.DecimalMin; import javax.validation.constraints.NotEmpty; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * @Author: yipeng * @Date: 2021/6/19 19:41 */ @Getter @Setter @ToString public class VaildVo { @NotEmpty(message = "fromUserName can't be empty") private String fromUserName; @NotEmpty(message = "toUserName can't be empty") private String toUserName; @DecimalMin(value= "100", message = "money can't be less than 100") @DecimalMax(value= "10000", message = "money can't exceed 10000") private Long money; }
DemoApplication
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication() public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
测试:
结论:
可实现简单的参数校验
这篇关于SpringBoot 使用javax.validation入参校验的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23Springboot应用的多环境打包入门
- 2024-11-23Springboot应用的生产发布入门教程
- 2024-11-23Python编程入门指南
- 2024-11-23Java创业入门:从零开始的编程之旅
- 2024-11-23Java创业入门:新手必读的Java编程与创业指南
- 2024-11-23Java对接阿里云智能语音服务入门详解
- 2024-11-23Java对接阿里云智能语音服务入门教程
- 2024-11-23JAVA对接阿里云智能语音服务入门教程
- 2024-11-23Java副业入门:初学者的简单教程
- 2024-11-23JAVA副业入门:初学者的实战指南