简体   繁体   English

getServletContext()。getAttribute()是否会重置值?

[英]getServletContext().getAttribute() resets value?

The following code is my sample servlet application 以下代码是我的示例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);
}

Whenever I make the first (localhost/value1) and second (localhost/value2) requests it (getServletContext().getAttribute("userEmails")) prints out the following 每当我发出第一个(localhost / value1)和第二个(localhost / value2)请求时(getServletContext().getAttribute("userEmails"))打印以下内容

[value1]
[value1,value2]

However whenever I make the third (localhost/value3) request it always converts LinkedList into boolean and prints out the following error 但是,每当我发出第三个(localhost / value3)请求时,它总是将LinkedList转换为布尔值并输出以下错误

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? 我不确定发生了什么,是否需要在web.xml中配置某些内容?

List.add() returns a boolean, so on the second time when you call userEmails.add(email) the attribute is replaced by a Boolean . List.add()返回一个布尔值,因此第二次调用userEmails.add(email)该属性将替换为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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM