2016-11-15 64 views
0

下面的代碼是我的樣本servlet應用程序getServletContext()。getAttribute()重置值?

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); 
} 

每當我做第一(本地主機/值1)和第二(本地主機/值2)請求它(getServletContext().getAttribute("userEmails"))打印出以下

[value1] 
[value1,value2] 

然而,每當我做第三個(localhost/value3)請求它總是將LinkedList轉換爲布爾值並打印出以下錯誤

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

我不確定發生了什麼,我是否需要在我的web.xml中配置一些東西?

回答

1

List.add()返回一個布爾值,所以在第二次調用userEmails.add(email)時,屬性被替換爲Boolean

在第一次將它放入上下文之後(除非要替換整個列表),不需要繼續設置該屬性。只是

userEmails.add(email); 
+0

感謝的人取代

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

;)它的工作原理 –

+1

好吧,如果我給了那些不起作用的答案也不會是非常有益的。 – Kayaman