我是Java Servlets的新手,对于我目前正在处理的应用程序,(某种没有转发或重定向类的代理)我想将对象保存到应用程序的上下文路径。
我知道有类似的问题,但我无法让它工作或我只是不理解。
我是否必须在web.xml中指定上下文路径? 我需要一个上下文监听器吗?
这是代码片段,但保存的Object中的对象为null; 如何将Object的当前状态保存到上下文路径?
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
if(this.getServletContext().getAttribute("oldConnector")==null){
Connector connection = new Connector();
connection.sendRequest(request);
this.getServletContext().setAttribute("oldConnector", connection);
}else{
((Connector)this.getServletContext().getAttribute("oldConnector")).sendResponse(response);
this.getServletContext().removeAttribute("oldConnector");
}
答案 0 :(得分:1)
HttpServletResponse的响应对象永远不会为空,因为它是在向您的servlet发出第一个请求时由Web容器创建的。
因此,属性" oldConnector"未设置,因此您将其值设为null。
建议:设置上下文属性" oldConnector"通过删除if(response == null)条件。并在另一个servlet中检索该属性或相同,然后在需要时将其删除。
下面的代码可以帮助您在评论中进行查询。
if(getServletContext().getAttribute("oldConnector") == null){
getServletContext().setAttribute("oldConnector", "old value");//dummy value added, replace it with your connection object.
System.out.println("oldConnector attribute has be set.");
}else{
getServletContext().removeAttribute("oldConnector");
System.out.println("oldConnector attribute has be removed");
}