开发者

Submitting array to Spring controller

开发者 https://www.devze.com 2023-03-23 12:15 出处:网络
I am trying to submit checkbox\'s values array to controller: @RequestMapping(value = \"/save\", method = RequestMethod.POST)

I am trying to submit checkbox's values array to controller:

@RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView save(@RequestBody UserForm form, HttpServletResponse response) { ... }

where UserForm has:

public class UserForm extends BaseForm {    
     private String[] role; ... }

I post with jquery's postJSON method. Everything fine when there are more then one selected checkbox - controller successfully translated it to array of String. But in case of only single checkbox is selected - serversife fails because the request parameters (especcially role field) has been passed as string and not array with single value. The checkboxes looks like:

<input type="checkbox" name=开发者_开发技巧"role" value="1" />
<input type="checkbox" name="role" value="2" />
etc...

Any help? Thank you

Additional:

$.postJSON(url + 'save',
                $('#userForm').serializeObject(),
                function(response) {
                    if (response.isAuthenticated && response.isAuthorized) {
                        if (response.hasErrors) {
                            $('#userForm').setErrors(response.errors);
                            hideWait();
                        }
                        else 
                            $('#filter').click();
                    }
                    else
                        redirectToLogin();
                });


Here is the solution that I found:

var data = $('#userForm').serializeObject();
        data.ur = new Array();
        $('#ur:checked').each(function() {
            data.ur.push($(this).val());
        });
        $.postJSON(url + 'save',
                data,
                function(response) {
                    if (response.isAuthenticated && response.isAuthorized) {
                        if (response.hasErrors) {
                            $('#userForm').setErrors(response.errors);
                            hideWait();
                        }
                        else 
                            showList(true);
                    }
                    else
                        redirectToLogin();
                });
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号