1. 程式人生 > >SpringMVC引數使用切面統一校驗

SpringMVC引數使用切面統一校驗

/**
 * 引數校驗統一處理
 */
@Log4j
@Aspect
@Component
public class ParamValidAspect {

    /**
     * 校驗錯誤處理
     * @param joinPoint
     * @param bindingResult
     * @return
     * @throws Throwable
     */
     // 切入點表示式,指向要執行校驗的方法
    @Around("execution(* com.**.controller.*.*(..)) && args(..,bindingResult)"
) public Object validateParam(ProceedingJoinPoint joinPoint, BindingResult bindingResult) throws Throwable { Object obj = null; if (bindingResult.hasErrors()) { // 有校驗錯誤 obj = getErrors(bindingResult); } else { // 沒有錯誤方法繼續執行 obj =
joinPoint.proceed(); } return obj; } /** * 解析校驗錯誤 * @param bindingResult * @return */ public ResponseEntity getErrors(BindingResult bindingResult) { List<String> errors = new ArrayList<>(); List<ObjectError> allErrors =
bindingResult.getAllErrors(); allErrors.forEach(x -> { FieldError fieldError = (FieldError) x; String msg = x.getDefaultMessage(); errors.add(fieldError.getField() + msg); }); // 自己封裝返回錯誤的格式 Result<Object> responseData = new Result<>(ResultEnum.EXCEPTION,"校驗錯誤", errors); ResponseEntity responseEntity = new ResponseEntity<Result>(responseData, HttpStatus.OK); return responseEntity; } }