Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Example:

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

How can I use @valid for the regNo parameter here?

like image 466
sofs1 Avatar asked Oct 07 '14 05:10

sofs1


People also ask

Can RequestBody and RequestParam be used at the same time in Spring MVC?

The @RequestBody is processed first. Spring will consume all the HttpServletRequest InputStream . When it then tries to resolve the @RequestParam , which is by default required , there is no request parameter in the query string or what remains of the request body, ie. nothing.

How do I pass multiple parameters in RequestParam?

You can capture multiple parameters in a single Map object using the @RequestParam . If all the query parameters in the URL have unique key names, then you can follow this below approach. We basically capture the query parameters of key-value pairs into Java Map object.


1 Answers

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<String, Object> validate(@Email(message="请输入合法的email地址") @RequestParam String email){
    Map<String, Object> result = new HashMap<String, Object>();
    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

like image 113
Guisong He Avatar answered Dec 06 '22 22:12

Guisong He