Why can't I use Valid parameter along with RequestParam in Spring MVC?

前端 未结 3 1527
北海茫月
北海茫月 2020-12-16 19:06

Example:

public String getStudentResult(@RequestParam(value = \"regNo\", required = true) String regNo, ModelMap model){

How can I use @v

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-16 19:25

    Late answer. I encounter this problem recently and find a solution. You can do it as follows, Firstly register a bean of MethodValidationPostProcessor:

    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        return new MethodValidationPostProcessor();
    }
    

    and then add the @Validated to the type level of your controller:

    @RestController
    @Validated
    public class FooController {
        @RequestMapping("/email")
        public Map validate(@Email(message="请输入合法的email地址") @RequestParam String email){
        Map result = new HashMap();
        result.put("email", email);
        return result;
        }
    }
    

    And if user requested with a invalid email address, the ConstraintViolationException will be thrown. And you can catch it with:

    @ControllerAdvice
    public class AmazonExceptionHandler {
    
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String handleValidationException(ConstraintViolationException e){
        for(ConstraintViolation s:e.getConstraintViolations()){
            return s.getInvalidValue()+": "+s.getMessage();
        }
        return "请求参数不合法";
    }
    

    }

    You can check out my demo here

提交回复
热议问题