以下代码是我的示例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转换为布尔值并输出以下错误

HTTP Status 500 - java.lang.Boolean cannot be cast to java.util.LinkedList


我不确定发生了什么,是否需要在web.xml中配置某些内容?

最佳答案

List.add()返回一个布尔值,因此第二次调用userEmails.add(email)时,该属性将替换为Boolean

第一次将属性放入上下文中后,无需继续设置属性(除非您要替换整个列表)。只需更换

getServletContext().setAttribute("userEmails", userEmails.add(email));




userEmails.add(email);

关于java - getServletContext()。getAttribute()是否会重置值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40619364/

10-10 22:40