以下代码是我的示例servlet应用程序
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);
}
每当我发出第一个(localhost / value1)和第二个(localhost / value2)请求它(getServletContext().getAttribute("userEmails"))
打印出以下内容
[value1]
[value1,value2]
但是每当我发出第三个(localhost / value3)请求时,它总是将LinkedList转换为boolean并打印出以下错误
HTTP Status 500 - java.lang.Boolean cannot be cast to java.util.LinkedList
我不知道发生了什么,我是否需要在我的web.xml中配置一些内容?
答案 0 :(得分:1)
List.add()
会返回一个布尔值,因此,当您致电userEmails.add(email)
时第二次,该属性会被Boolean
替换。
在第一次将属性放入上下文后,您不需要继续设置属性(除非您想要替换整个列表)。只需替换
getServletContext().setAttribute("userEmails", userEmails.add(email));
与
userEmails.add(email);