I am building a bootstrap multiselect tool like this:
The selected values in multiselect tool are first converted into a javascript array, like this:
var authors = [];
$("#selectAuthors option:selected").each(function(i, value) {
authors.push($(this).val());
});
Then this array is passed to servlet using ajax:
$.ajax({
method : "POST",
url : "../addBook",
data : {
addTitle : $("#addTitle").val(),
addPublisher : $("#selectPublisher").val(),
addAuthors : JSON.stringify(authors),
}
})
And in the servlet, the array is parsed to a java string array:
String[] authorNames = request.getParameterValues("addAuthors");
The problem is, the java string array I got in the servlet is not exactly I wanted. For example, If I select "author1" and "author2" in multiselect tool:
Expected string array I should get:
{"author1", "author2"}, string length: 2
The string I actually get:
{"["author1", "author2"]"}, string length: 1
If I just select one option in multiselect tool, like "author". In servlet, I will get this:
Print out authorNames[0]: ["author"]
Print out authorNames[0].length: 10
//The legnth of "author" is 6, but the length of "["author"]" is 10
Can you explain where I did wrong? Thanks in advance.
I parse "authors" to string first, then use string.split(",") in servlet to convert the string to string array.