Commit f3d00d84 by 周田

feat(core): 参数校验

parent 5eb7b9a3
...@@ -19,10 +19,6 @@ ...@@ -19,10 +19,6 @@
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
...@@ -30,6 +26,10 @@ ...@@ -30,6 +26,10 @@
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
...@@ -2,6 +2,7 @@ package org.linker.springboot; ...@@ -2,6 +2,7 @@ package org.linker.springboot;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@SpringBootApplication @SpringBootApplication
public class SpringbootApplication { public class SpringbootApplication {
......
...@@ -8,14 +8,11 @@ public enum ServiceExceptionEnum { ...@@ -8,14 +8,11 @@ public enum ServiceExceptionEnum {
// ========== 系统级别 ========== // ========== 系统级别 ==========
SUCCESS(0, "成功"), SUCCESS(0, "成功"),
SYS_ERROR(2001001000, "服务端发生异常"), SYS_ERROR(2001001000, "服务端发生异常"),
PARAM_VALIDATE_ERROR(2001001002, "参数校验错误"),
MISSING_REQUEST_PARAM_ERROR(2001001001, "参数缺失"), MISSING_REQUEST_PARAM_ERROR(2001001001, "参数缺失"),
// ========== 用户模块 ========== // ========== 用户模块 ==========
USER_NOT_FOUND(1001002000, "用户不存在"), USER_NOT_FOUND(1001002000, "用户不存在"),
// ========== 订单模块 ==========
// ========== 商品模块 ==========
; ;
/** /**
......
package org.linker.springboot.controller; package org.linker.springboot.controller;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import org.linker.springboot.constants.ServiceExceptionEnum; import org.linker.springboot.constants.ServiceExceptionEnum;
import org.linker.springboot.core.exception.ServiceException; import org.linker.springboot.core.exception.ServiceException;
import org.linker.springboot.core.vo.CommonResult; import org.linker.springboot.core.vo.CommonResult;
...@@ -10,6 +13,7 @@ import org.linker.springboot.vo.UserVO; ...@@ -10,6 +13,7 @@ import org.linker.springboot.vo.UserVO;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.ArrayList; import java.util.ArrayList;
...@@ -21,6 +25,7 @@ import java.util.UUID; ...@@ -21,6 +25,7 @@ import java.util.UUID;
*/ */
@RestController @RestController
@RequestMapping("/users") @RequestMapping("/users")
@Validated
public class UserController { public class UserController {
@Autowired @Autowired
...@@ -160,4 +165,16 @@ public class UserController { ...@@ -160,4 +165,16 @@ public class UserController {
logger.info("[exception03]"); logger.info("[exception03]");
throw new ServiceException(ServiceExceptionEnum.USER_NOT_FOUND); throw new ServiceException(ServiceExceptionEnum.USER_NOT_FOUND);
} }
@GetMapping("/get_validate")
public CommonResult<Integer> validate01(@NotNull(message = "参数 id 不能为空") Integer id) {
logger.info("[getValidate] id: {}", id);
return CommonResult.success(id);
}
@PostMapping("/validate")
public CommonResult<UserVO> validate02(@Valid @RequestBody UserVO userVO) {
logger.info("[validate] userVO: {}", userVO.toString());
return CommonResult.success(userVO);
}
} }
package org.linker.springboot.core.web; package org.linker.springboot.core.web;
import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolationException;
import org.linker.springboot.core.exception.ServiceException; import org.linker.springboot.core.exception.ServiceException;
import org.linker.springboot.constants.ServiceExceptionEnum; import org.linker.springboot.constants.ServiceExceptionEnum;
import org.linker.springboot.core.vo.CommonResult; import org.linker.springboot.core.vo.CommonResult;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ExceptionHandler;
...@@ -56,4 +59,33 @@ public class GlobalExceptionHandler { ...@@ -56,4 +59,33 @@ public class GlobalExceptionHandler {
ServiceExceptionEnum.SYS_ERROR.getMessage()); ServiceExceptionEnum.SYS_ERROR.getMessage());
} }
@ResponseBody
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public CommonResult methodArgumentNotValidExceptionHandler(HttpServletRequest req, MethodArgumentNotValidException e) {
// 记录异常日志
logger.error("[exceptionHandler]", e);
// 拼接错误
StringBuilder detailMessage = new StringBuilder();
for (ObjectError objectError : e.getAllErrors()) {
// 使用 ; 分隔多个错误
if (detailMessage.length() > 0) {
detailMessage.append(";");
}
// 拼接内容到其中
detailMessage.append(objectError.getDefaultMessage());
}
// 返回 ERROR CommonResult
return CommonResult.error(ServiceExceptionEnum.PARAM_VALIDATE_ERROR.getCode(),
ServiceExceptionEnum.PARAM_VALIDATE_ERROR.getMessage() + ":" + detailMessage);
}
@ResponseBody
@ExceptionHandler(value = ConstraintViolationException.class)
public CommonResult ConstraintViolationExceptionHandler(HttpServletRequest req, ConstraintViolationException e) {
// 记录异常日志
logger.error("[exceptionHandler]", e);
// 返回 ERROR CommonResult
return CommonResult.error(ServiceExceptionEnum.PARAM_VALIDATE_ERROR.getCode(),
ServiceExceptionEnum.PARAM_VALIDATE_ERROR.getMessage() + ":" + e.getMessage());
}
} }
package org.linker.springboot.vo; package org.linker.springboot.vo;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
/** /**
* 用户 VO * 用户 VO
*/ */
...@@ -8,10 +12,14 @@ public class UserVO { ...@@ -8,10 +12,14 @@ public class UserVO {
/** /**
* 编号 * 编号
*/ */
@NotNull(message = "编号不能为空")
@Min(1)
private Integer id; private Integer id;
/** /**
* 账号 * 账号
*/ */
@NotNull(message = "账号不能为空")
@Size(min = 4, max = 10, message = "账号长度必须在 {min} - {max} 之间")
private String username; private String username;
public Integer getId() { public Integer getId() {
...@@ -32,4 +40,11 @@ public class UserVO { ...@@ -32,4 +40,11 @@ public class UserVO {
return this; return this;
} }
@Override
public String toString() {
return "UserVO{" +
"id=" + id +
", username='" + username + '\'' +
'}';
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment