2012-02-25 45 views
0

我想將一個HashMap放到ServletContext對象上,以便我可以從不同上下文中的一個war文件訪問它。我還沒有嘗試從多重上下文訪問它。我只是試圖從同一個servlet訪問,我似乎無法獲得價值。兩種方法都返回nullpointerexceptions。ServletContext - 返回null的應用程序作用域會話對象

public class TestServlet extends HttpServlet{ 

private static final long serialVersionUID = -8002515227440283546L; 

public void doGet(HttpServletRequest request, HttpServletResponse response) 
throws IOException{ 
    PrintWriter out = response.getWriter(); 

    HashMap<String ,String> hm = new HashMap<String, String>(); 
    hm.put("1", "1"); 

    this.getServletContext().setAttribute("usernamanager", hm); 
    this.getServletConfig().getServletContext().setAttribute("usernamanager", hm); 

    HashMap newMap2 = (HashMap) this.getServletConfig().getServletContext().getAttribute("usermanager"); 
    HashMap newMap3 = (HashMap) this.getServletContext().getAttribute("usermanager"); 

    out.println("App1 - " + newMap2.get("1")); 
    out.println("App1 - " + newMap3.get("1")); 
} 
} 

servlet部署在Tomcat容器上。

+0

屬性名稱不匹配......「usernamanager」和「的UserManager」 – Hamed 2012-02-25 17:12:06

+0

你是對的。這是我的一個愚蠢的錯誤。謝謝 – ziggy 2012-02-25 17:18:55

+0

請張貼此作爲答案和虐待接受。 – ziggy 2012-02-25 17:31:30

回答

1

屬性名應該匹配:usernamanager VS usermanager