gpt4 book ai didi

java - getServletContext().getAttribute() 重置值?

转载 作者:行者123 更新时间:2023-12-01 09:15:02 24 4
gpt4 key购买 nike

以下代码是我的示例 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 中配置某些内容吗?

最佳答案

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

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

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

userEmails.add(email);

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com