Reputation: 71
The following code is my sample servlet application
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userEmail = request.getPathInfo().split("/")[1];
saveEmails(response, userEmail);
}
protected void saveEmails(HttpServletResponse response, String email) {
ArrayList<String> userEmails = (ArrayList<String>)getServletContext().getAttribute("userEmails");
if (userEmails == null) {
System.out.println("creating a new linked list");
ArrayList<String> newUserEmails = new ArrayList<String>();
newUserEmails.add(email);
getServletContext().setAttribute("userEmails", newUserEmails);
} else {
System.out.println("appending new email into linked list");
getServletContext().setAttribute("userEmails", userEmails.add(email));
}
System.out.println(userEmails);
}
Whenever I make the first (localhost/value1) and second (localhost/value2) requests it (getServletContext().getAttribute("userEmails"))
prints out the following
[value1]
[value1,value2]
However whenever I make the third (localhost/value3) request it always converts LinkedList into boolean and prints out the following error
HTTP Status 500 - java.lang.Boolean cannot be cast to java.util.LinkedList
I'm not sure what's going on, do I need to configure something in my web.xml?
Upvotes: 0
Views: 513
Reputation: 73578
List.add()
returns a boolean, so on the second time when you call userEmails.add(email)
the attribute is replaced by a Boolean
.
You don't need to keep setting the attribute after you've put it in the context the first time (unless you want to replace the whole list). Just replace
getServletContext().setAttribute("userEmails", userEmails.add(email));
with
userEmails.add(email);
Upvotes: 1