我是 servlet 的新手,我正在关注本教程,一切正常,但是当我从请求中删除一个属性时,它不会触发正确的事件,这是我的代码。
我在 SO 上找不到类似的案例。
小服务程序
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
ServletContext ctx = request.getServletContext();
ctx.setAttribute("User", "Pankaj");
String user = (String) ctx.getAttribute("User");
System.out.println("removing attr");
ctx.removeAttribute("User");
HttpSession session = request.getSession();
session.invalidate();
PrintWriter out = response.getWriter();
out.write("Hi "+user);
}
听众
@WebListener
public class AppContextAttributeListener implements
ServletRequestAttributeListener
{
public void attributeAdded(ServletRequestAttributeEvent arg0) {
System.out.println("ServletContext attribute added::{"
+ arg0.getName() + ","
+ arg0.getValue() + "}");
}
public void attributeRemoved(ServletRequestAttributeEvent arg0) {
System.out.println("here");
System.out.println("ServletContext attribute removed::{"
+ arg0.getName() + ","
+ arg0.getValue() + "}");
}
public void attributeReplaced(ServletRequestAttributeEvent arg0) {
System.out.println("ServletContext attribute replaced::{"
+ arg0.getName() + ","
+ arg0.getValue() + "}");
}
}
预期产出
ServletRequest initialized. Remote IP=0:0:0:0:0:0:0:1%0
ServletContext attribute added::{User,Pankaj}
removing attr
here
ServletContext attribute removed::{User,Pankaj}
Session Created:: ID=8805E7AE4CCCF98AFD60142A6B300CD6
Session Destroyed:: ID=8805E7AE4CCCF98AFD60142A6B300CD6
ServletRequest destroyed. Remote IP=0:0:0:0:0:0:0:1%0
我的输出
ServletRequest initialized. Remote IP=0:0:0:0:0:0:0:1%0
ServletContext attribute added::{User,Pankaj}
removing attr
Session Created:: ID=8805E7AE4CCCF98AFD60142A6B300CD6
Session Destroyed:: ID=8805E7AE4CCCF98AFD60142A6B300CD6
ServletRequest destroyed. Remote IP=0:0:0:0:0:0:0:1%0
我无法触发attributeRemoved() 虽然attributeAdded() 正在打印,这意味着监听器定义明确!
这里有什么问题?我正在使用 tomcat 7 和 servlet 3