I have a JSP file in which jQuery is supposed to send a POST request containing the elements (categories) I have ticked in a multi select box to the server. The server will analyse the string containing all ticked categories and return a list of subjects, for the jQuery to analyse it and display the subjects in another multi select.
The only problem is, when I tick no category, the jQuery does send an empty parameter to the server, but the server never detects it as null!
I tried an alert that does display “”, but it just won’t work! The server crashes pretexting a NullPointerException related to the code in the if condition obviously.
Here’s my code:
=== JSP ===
<script>
$(document).ready(function ()
{
$('#subjectCategories').change(function()
{
var selectedOptions = $('#subjectCategories option:selected');
var selectedValues = $.map(selectedOptions ,function(option)
{
return option.value;
}).join(',');
$.ajax({
type: "POST",
url: "creation",
data: 'selectedSubjectCategories='+selectedValues,
success: function(data)
{
if (data!=null)
{
//alert("\""+data+"\"");
var subjects = data.split(',');
var select = $('#subjectslist');
$('#subjectslist').children().remove();
$.each(subjects, function(key, subject)
{
if (select.find('option[value="' + subject + '"]').length === 0 && subject!="")
{
//Ajouter la nouvelle catégorie dans la liste
$('<option>', {
value: subject,
text: subject
}).appendTo(select);
}
});
}
else
{
$('#subjectslist').children().remove();
}
}
});
}
);
}).change();
</script>
=== SERVLET ===
if (request.getParameter("selectedSubjectCategories")!=null)
{
String[] categoryList = request.getParameter("selectedSubjectCategories").split(",");
ArrayList<String> pourDoublons = new ArrayList<String>();
String subjectsToShow = new String();
for (int i=0; i<categoryList.length; i++)
{
if (categorySubjectsHashMap.containsKey(categoryList[i]))
{
ArrayList<String> subjectsOfCategory = categorySubjectsHashMap.get(categoryList[i]);
for (int j=0; j<subjectsOfCategory.size(); j++)
{
if (!pourDoublons.contains(subjectsOfCategory.get(j)))
{
subjectsToShow += subjectsOfCategory.get(j)+",";
pourDoublons.add(subjectsOfCategory.get(j));
}
}
}
}
categoryList = null;
pourDoublons = null;
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(subjectsToShow.substring(0,subjectsToShow.length()-1));
}
else
{
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("");
}
Why can’t my parameter be detected as null? I also tried .equals(null) and a lot of stuff like that, but nothing worked! 🙁
Thanks in advance.
worked fine. 🙂