我是Java servlet的新手,对于我目前正在开发的应用程序(某种没有转发或重定向类的代理),我想将对象保存到应用程序的上下文路径中。
我知道有类似的问题,但是我不能让它工作或者我只是不理解它。
我必须在web.xml中指定上下文路径吗?我需要一个上下文侦听器吗?
这是代码片段,但是保存的Object中的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");
}
HttpServletResponse的响应对象永远不会是空的,因为它是由web容器在第一次向servlet发出请求时创建的
因此,没有设置属性"oldConnector",因此您将得到它的值为null。
建议:通过删除if(response==null)条件设置上下文属性"oldConnector"。并在另一个servlet或相同的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");
}