Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

any way to get BindingResult for @RequestParam?

I'm using Spring 3 Portlet MVC. Validation/binding in just MVC should be the same.

I've got just a single int form field. When I'm doing

void doSmth(MyForm form, BindingResult bindingResult) throws ... {
  int bindErrors = bindingResult.getErrorCount())
  ...

and submitting a field value that can't be parsed as int this method gets executed and bindErrors is 1. Form field value that this method receives is 0. That's great.

But creating a form just to contain a single field is not great.

I'm changing the code to:

void doSmth(@RequestParam int userId, BindingResult bindingResult) ... {
  int bindErrors = bindingResult.getErrorCount())
  ...

and getting Portlet not available message in browser and this Exception:

org.springframework.web.portlet.FrameworkPortlet processRequest Could not complete request org.springframework.beans.TypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: "q"

Question: is there any way to proceed with method execution and to process binding errors in it even if @RequestParam type conversion fails? I tried making @RequestParam not required and providing a default value to it - didn't help.

like image 872
Oleg Mikheev Avatar asked Jan 26 '12 14:01

Oleg Mikheev


1 Answers

The Spring reference allows BindingResult only for command or form objects.

org.springframework.validation.Errors / org.springframework.validation.BindingResult validation results for a preceding command or form object (the immediately preceding method argument).

(15.3.2.3 Supported handler method arguments and return types)

So you may need to implement it by your own.

  • I think you can try to use a Custom MethodArgumentResolver (see this blog for an example).
  • There is an other current still open stack overflow question: How to customize parameter names when binding spring mvc command objects -- I have the feeling that an solution for this question may can give you an good input for your solution.

or you wrap your single int in a command object and the use the binding result on this object (an example can be found here: https://stackoverflow.com/a/13407434/280244)

like image 183
Ralph Avatar answered Sep 21 '22 13:09

Ralph