5

I'm working on spring mvc application, where I should aplly validation based on Spring MVC validator but validate but AJAX request. So, when I send just single data everything is ok, Spring is mapping data from request into object and validate it. But when I add new paramener which is array, Spring thows a exception:

java.lang.NumberFormatException: For input string: ""

My User class:

public class User
{
    @NotEmpty
    private String login;

    private List<Department> departments;
}

My controller:

@Controller
public class UserController
{
    @RequestMapping(value = "/save")
    public ModelAndView save(@Valid @ModelAttribute("user") final User user,
            BindingResult result) throws Exception
    {
       // do action
    }
}

My AJAX request(POST):

http://localhost:8080/myApp/user/save?departments%5B%5D=1&departments%5B%5D=3&id=&login=Test

My JS(jQuery):

var form = $('.add-form');
var fields = form.find('input');
var data = {};
// get valud from input fields
for (var i = 0; i < fields.length; i++) {
    var $item = $(fields[i]);
    data[$item.attr('name')] = $item.val();
}
// get value from list as array
data['departments'] = form.find('#departmentsSelector').val();
$.ajax({
    type: "POST",
    url: "user/save",
    data: data,
    success: function(response){
        // do something
    }
})

It looks like Spring is trying to parse name of parameter departments[] as a parameter with a value instead of use value of this parameter.

Can anyone help me with this?

2
  • I suspect "id" field is the culprit here. If you see in the post request "&id=&" means empty string is being passed as the value of id. If id is of type integer(as it looks like) then NumberFormatException is thrown. Commented Aug 5, 2014 at 9:35
  • No, it's OK. Problem in departments[]. Commented Aug 5, 2014 at 9:44

1 Answer 1

4

So, I've found an error, the problem was in [] for parameter departments. If you use traditional: true for jQuery AJAX request than array variable will not contain [] in name and Spring mapping it in POJO.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.