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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With