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

Example:

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

How can I use @valid for regNo parameter here?

+6
source share
3 answers

Late answer. I recently ran into this problem and found a solution. You can do this as follows: First register the bean from MethodValidationPostProcessor :

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

and then add @Validated to the level type 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 the user requested with an invalid email address, a ConstraintViolationException will be selected. And you can catch it:

 @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 my demo here.

+5
source

@Valid can be used to check beans. I have not seen it used for single string parameters. Also for this, a validator setting is required.

@Valid annotations are part of the standard JSR-303 Bean APIs and are not a Spring construct. Spring MVC will validate the @Valid object after binding as long as the corresponding validator has been configured.

Link: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html

+3
source

one way to do this is to write a Wrapper Bean as follows:

  public class RegWrapperBean{ @NotNull String regNo ; public String getRegNo(){ return regNo ; } public void setRegNo(String str){ this.regNo=str; } } 

and your handler method will look like this:

  @RequestMapping(value="/getStudentResult", method=RequestMethod.POST) public String getStudentResult(@Valid @ModelAttribute RegWrapperBean bean, BindingResult validationResult, Model model) { } 

and refer to these answers here and here .

Hope this helps.

+1
source

Source: https://habr.com/ru/post/976332/


All Articles