Spring Check @MVC and @RequestParam

I would like to use the @RequestParam annotation as follows:

@RequestMapping public void handleRequest( @RequestParam("page") int page ) { ... } 

However, I want to show page 1 if the user is messing with the URL parameters and trying to go to the "abz" page or something not numerical. Right now, the best I can do for Spring to do this is to return 500. Is there a way to completely override this behavior without having to accept a parameter as a string?

I looked through the @ExceptionHandler annotation but it doesn't seem to do anything when I set up using @ExceptionHandler(TypeMismatchException.class) . Not sure why not.

Suggestions?

PS Bonus question: Spring MVC is called Spring MVC. Is Spring MVC with annotations called only Spring @MVC? Google sees them as the same name, which is annoying.

+7
spring spring-mvc
source share
2 answers

Since Spring 3.0, you can install ConversionService . @InitBinder value indicates a specific parameter to apply this service to:

 @InitBinder("page") public void initBinder(WebDataBinder binder) { FormattingConversionService s = new FormattingConversionService(); s.addFormatterForFieldType(Integer.class, new Formatter<Integer>() { public String print(Integer value, Locale locale) { return value.toString(); } public Integer parse(String value, Locale locale) throws ParseException { try { return Integer.valueOf(value); } catch (NumberFormatException ex) { return 1; } } }); binder.setConversionService(s); } 
+8
source share

ConversionService is a nice solution, but it doesn't matter if you pass an empty string to your request, for example ?page= . ConversionService just doesn't get called at all, but page set to null (in case of Integer ) or an Exception (in case of int )

This is my preferred solution:

 @RequestMapping public void handleRequest( HttpServletRequest request ) { int page = ServletRequestUtils.getIntParameter(request, "page", 1); } 

This way you always have a valid int parameter.

+10
source share

All Articles