forked from rstyro/Springboot
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
10 changed files
with
366 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
<?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.3.2.RELEASE</version> | ||
<relativePath/> <!-- lookup parent from repository --> | ||
</parent> | ||
<groupId>top.lrshuai</groupId> | ||
<artifactId>springboot-validator</artifactId> | ||
<version>0.0.1-SNAPSHOT</version> | ||
<name>springboot-validator</name> | ||
<description>自定义注解校验参数</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.springframework.boot</groupId> | ||
<artifactId>spring-boot-starter-test</artifactId> | ||
<scope>test</scope> | ||
</dependency> | ||
|
||
<dependency> | ||
<groupId>org.projectlombok</groupId> | ||
<artifactId>lombok</artifactId> | ||
<version>1.18.20</version> | ||
</dependency> | ||
</dependencies> | ||
|
||
<build> | ||
<plugins> | ||
<plugin> | ||
<groupId>org.springframework.boot</groupId> | ||
<artifactId>spring-boot-maven-plugin</artifactId> | ||
</plugin> | ||
</plugins> | ||
</build> | ||
|
||
</project> |
13 changes: 13 additions & 0 deletions
13
springboot-validator/src/main/java/top/lrshuai/validator/SpringbootValidatorApplication.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
package top.lrshuai.validator; | ||
|
||
import org.springframework.boot.SpringApplication; | ||
import org.springframework.boot.autoconfigure.SpringBootApplication; | ||
|
||
@SpringBootApplication | ||
public class SpringbootValidatorApplication { | ||
|
||
public static void main(String[] args) { | ||
SpringApplication.run(SpringbootValidatorApplication.class, args); | ||
} | ||
|
||
} |
64 changes: 64 additions & 0 deletions
64
springboot-validator/src/main/java/top/lrshuai/validator/annotation/MatchValidator.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
package top.lrshuai.validator.annotation; | ||
|
||
import org.springframework.util.StringUtils; | ||
|
||
import javax.validation.ConstraintValidator; | ||
import javax.validation.ConstraintValidatorContext; | ||
import java.util.Arrays; | ||
import java.util.HashSet; | ||
import java.util.Set; | ||
|
||
/** | ||
* 自定义验证器 | ||
*/ | ||
public class MatchValidator implements ConstraintValidator<MatchValue, String> { | ||
|
||
/** | ||
* 接收注解传过来的值 | ||
*/ | ||
private Set<String> enumName=new HashSet<>(); | ||
|
||
/** | ||
* 初始化方法,可以获取注解的参数信息 | ||
*/ | ||
@Override | ||
public void initialize(MatchValue matchValue) { | ||
try { | ||
String[] values = matchValue.values(); | ||
if(values.length>0){ | ||
for (String item:values){ | ||
enumName.add(item); | ||
} | ||
} | ||
Class<?extends Enum>[] enums = matchValue.enums(); | ||
if(enums.length>0){ | ||
Enum[] enumConstants = Arrays.stream(enums).findFirst().get().getEnumConstants(); | ||
for (Enum e:enumConstants){ | ||
enumName.add(e.name()); | ||
} | ||
} | ||
}catch (Throwable e){ | ||
e.printStackTrace(); | ||
} | ||
|
||
} | ||
|
||
/** | ||
* 校验值 | ||
* @param value 参数的值信息 | ||
* @param context 上下文对象,可以禁用默认提示模板,然后更改提示模板 | ||
* @return boolean | ||
*/ | ||
@Override | ||
public boolean isValid(String value, ConstraintValidatorContext context) { | ||
if(!StringUtils.isEmpty(value)){ | ||
for(String name:enumName){ | ||
if(name.equals(value)){ | ||
return true; | ||
} | ||
} | ||
return false; | ||
} | ||
return true; | ||
} | ||
} |
36 changes: 36 additions & 0 deletions
36
springboot-validator/src/main/java/top/lrshuai/validator/annotation/MatchValue.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
package top.lrshuai.validator.annotation; | ||
|
||
import javax.validation.Constraint; | ||
import javax.validation.Payload; | ||
import java.lang.annotation.*; | ||
|
||
/** | ||
* 自定义注解 | ||
*/ | ||
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, | ||
ElementType.CONSTRUCTOR, ElementType.PARAMETER}) | ||
@Retention(RetentionPolicy.RUNTIME) | ||
@Documented | ||
// 指定此注解的实现,即:验证器 | ||
@Constraint(validatedBy = MatchValidator.class) | ||
public @interface MatchValue { | ||
|
||
/** | ||
* 固定的值校验 | ||
*/ | ||
String[] values() default {}; | ||
|
||
/** | ||
* 校验不通过提示 | ||
*/ | ||
String message() default ""; | ||
|
||
/** | ||
* 通过枚举类校验 | ||
*/ | ||
Class<? extends Enum>[] enums() default {}; | ||
|
||
Class<?>[] groups() default {}; | ||
|
||
Class<? extends Payload>[] payload() default {}; | ||
} |
88 changes: 88 additions & 0 deletions
88
springboot-validator/src/main/java/top/lrshuai/validator/commons/Result.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
package top.lrshuai.validator.commons; | ||
|
||
import org.springframework.util.ObjectUtils; | ||
|
||
import java.util.HashMap; | ||
import java.util.Map; | ||
|
||
|
||
/** | ||
* 随便封装了下接口返回 模板类 | ||
*/ | ||
public class Result extends HashMap<String, Object> { | ||
|
||
private static final long serialVersionUID = 1L; | ||
|
||
/** | ||
* 状态 | ||
*/ | ||
public static final String STATUS="status"; | ||
/** | ||
* 信息 | ||
*/ | ||
public static final String MESSAGE="message"; | ||
/** | ||
* 数据体 | ||
*/ | ||
public static final String DATA="data"; | ||
|
||
public Result() { | ||
put(STATUS, 200); | ||
put(MESSAGE, "ok"); | ||
} | ||
|
||
public static Result error() { | ||
return error("500", "系统错误,请联系管理员"); | ||
} | ||
|
||
public static Result error(String msg) { | ||
return error("500", msg); | ||
} | ||
|
||
public static Result error(String status, String msg) { | ||
Result r = new Result(); | ||
r.put(STATUS, status); | ||
r.put(MESSAGE, msg); | ||
return r; | ||
} | ||
|
||
public static Result ok(Map<String, Object> map) { | ||
Result r = new Result(); | ||
r.putAll(map); | ||
return r; | ||
} | ||
public static Result ok(Object data) { | ||
Result r = new Result(); | ||
r.put(DATA,data); | ||
return r; | ||
} | ||
|
||
public static Result ok() { | ||
return new Result(); | ||
} | ||
|
||
@Override | ||
public Result put(String key, Object value) { | ||
super.put(key, value); | ||
return this; | ||
} | ||
|
||
public Result putData(String key, Object value) { | ||
Object data = getData(); | ||
if(ObjectUtils.isEmpty(data)){ | ||
data=new HashMap<String,Object>(); | ||
this.put(DATA,data); | ||
} | ||
if(data instanceof HashMap){ | ||
((HashMap) data).put(key,value); | ||
}else { | ||
throw new RuntimeException("不是map类型,无法添加其他属性"); | ||
} | ||
return this; | ||
} | ||
|
||
public Object getData(){ | ||
return this.get(DATA); | ||
} | ||
|
||
} |
20 changes: 20 additions & 0 deletions
20
springboot-validator/src/main/java/top/lrshuai/validator/controller/TestController.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
package top.lrshuai.validator.controller; | ||
|
||
import org.springframework.validation.annotation.Validated; | ||
import org.springframework.web.bind.annotation.PostMapping; | ||
import org.springframework.web.bind.annotation.RequestBody; | ||
import org.springframework.web.bind.annotation.RestController; | ||
import top.lrshuai.validator.dto.TestDto; | ||
|
||
import javax.validation.Valid; | ||
|
||
@Validated | ||
@RestController | ||
public class TestController { | ||
|
||
@PostMapping("/test") | ||
public Object test(@RequestBody @Valid TestDto dto){ | ||
System.out.println("dto="+dto.toString()); | ||
return "ok"; | ||
} | ||
} |
27 changes: 27 additions & 0 deletions
27
springboot-validator/src/main/java/top/lrshuai/validator/dto/TestDto.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
package top.lrshuai.validator.dto; | ||
|
||
import lombok.Data; | ||
import lombok.experimental.Accessors; | ||
import top.lrshuai.validator.annotation.MatchValue; | ||
|
||
import javax.validation.constraints.Max; | ||
import javax.validation.constraints.Min; | ||
import javax.validation.constraints.NotBlank; | ||
import javax.validation.constraints.NotNull; | ||
|
||
|
||
@Data | ||
@Accessors(chain = true) | ||
public class TestDto { | ||
|
||
@NotBlank(message = "name不能为空") | ||
private String name; | ||
|
||
@MatchValue(values = {"男","女"},message = "sex参数无效") | ||
private String sex; | ||
|
||
@NotNull(message = "age 不能为空") | ||
@Min(value = 1,message = "age最小是1") | ||
@Max(value = 200,message = "age最大为200") | ||
private Integer age; | ||
} |
52 changes: 52 additions & 0 deletions
52
...validator/src/main/java/top/lrshuai/validator/exception/GlobalExceptionHandlerAdvice.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
package top.lrshuai.validator.exception; | ||
|
||
import lombok.extern.slf4j.Slf4j; | ||
import org.springframework.http.converter.HttpMessageNotReadableException; | ||
import org.springframework.util.StringUtils; | ||
import org.springframework.validation.BindingResult; | ||
import org.springframework.validation.FieldError; | ||
import org.springframework.web.bind.MethodArgumentNotValidException; | ||
import org.springframework.web.bind.MissingServletRequestParameterException; | ||
import org.springframework.web.bind.annotation.ControllerAdvice; | ||
import org.springframework.web.bind.annotation.ExceptionHandler; | ||
import org.springframework.web.bind.annotation.ResponseBody; | ||
import top.lrshuai.validator.commons.Result; | ||
|
||
import javax.servlet.http.HttpServletRequest; | ||
import javax.validation.ConstraintViolationException; | ||
import javax.xml.bind.ValidationException; | ||
|
||
/** | ||
* 描述:全局统一异常处理 | ||
*/ | ||
@Slf4j | ||
@ControllerAdvice | ||
public class GlobalExceptionHandlerAdvice { | ||
|
||
/** | ||
* 验证异常 | ||
*/ | ||
@ExceptionHandler(value = {MethodArgumentNotValidException.class}) | ||
@ResponseBody | ||
public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { | ||
BindingResult bindingResult = e.getBindingResult(); | ||
String errorMsg = ""; | ||
for (FieldError fieldError : bindingResult.getFieldErrors()) { | ||
errorMsg += fieldError.getDefaultMessage() + ";"; | ||
} | ||
if (!StringUtils.isEmpty(errorMsg)) { | ||
log.error("MethodArgumentNotValidException:" + errorMsg); | ||
return Result.error(errorMsg); | ||
} | ||
return Result.error(); | ||
} | ||
|
||
@ExceptionHandler(Exception.class) | ||
@ResponseBody | ||
public Result handlerException(Exception e) { | ||
log.error("系统异常:" + e.getMessage(), e); | ||
return Result.error(); | ||
} | ||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
|
13 changes: 13 additions & 0 deletions
13
...ot-validator/src/test/java/top/lrshuai/validator/SpringbootValidatorApplicationTests.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
package top.lrshuai.validator; | ||
|
||
import org.junit.jupiter.api.Test; | ||
import org.springframework.boot.test.context.SpringBootTest; | ||
|
||
@SpringBootTest | ||
class SpringbootValidatorApplicationTests { | ||
|
||
@Test | ||
void contextLoads() { | ||
} | ||
|
||
} |