views:

33

answers:

1

If a HTML form contains multiple input fields:

 <form>
 <input id="in1" type="text" value="one">
 <input id="in2" type="text" value="two">
 <input id="in3" type="text" value="three">
 </form>

and is passed to a Spring controller as a serialized form like this:

new Ajax.Request('/doajax', 
{asynchronous:true, evalScripts:true, 
parameters: $('ajax_form').serialize(true)});

what Java type would be needed to read the serialized ajax_form in a Spring 3 controller?

@RequestMapping("/doajax")
@ResponseBody
public String doAjax(@RequestParam <?Type> ajaxForm 
{
 // do something
}
+1  A: 

First of all, you use form fields without names, so serialize() actually produces an empty result. Add names:

<form> 
 <input name = "in1" id="in1" type="text" value="one"> 
 <input name = "in2" id="in2" type="text" value="two"> 
 <input name = "in3" id="in3" type="text" value="three"> 
</form>

I guess you use Prototype, so parameters: $('ajax_form').serialize(true) produces a URL-encoded representation of the form (and also you don't need true here, it adds unnecessary conversion). Since @RequestParam can't bind complex types, you can bind fields as separate parameters:

public String doAjax(@RequestParam("in1") String in1, 
    @RequestParam("in2") String in2, @RequestParam("in2") String in2)

Also you can create a class to hold form data and pass it as a model attribute:

public class AjaxForm {
    private String in1;
    private String in2;
    private String in3;

    ... getters, setters ...
}

-

public String doAjax(AjaxForm form)
axtavt
That worked. Awesome! Thank you.
Bowe
The @RequestParams work but the AjaxForm is not working. It doesn't seem to know how to map the form fields to the class.
Bowe
@Bowe: It should work. Make sure that names of the class properties match the names of the form fields, and that the class have properly named getters and setters.
axtavt
@axtavt: Some of the form fields have underscores. So the HTML form field is called "order_id" but the class field is called "orderId". Is there any way to associate these without renaming the HTML? With @RequestParam, you can do this by saying: @RequestParam(value="order_id") String orderId
Bowe
I've posted a follow-up question: http://stackoverflow.com/questions/3646314/with-a-form-class-in-spring-3-how-do-you-map-a-html-form-field-called-order-id
Bowe