HttpSessionBindingListner方法未被调用

时间:2014-01-22 04:15:31

标签: java servlets

我正在尝试HttpSessionBindingListener示例,但事件未触发。我在这做错了什么。

以下是我尝试设置的Attribute类的代码以及servlet类的代码。

servlet正在运行,但没有显示我期待的输出。

    public class SimpleAttribute implements HttpSessionBindingListener {

        PrintWriter writer;

        public  SimpleAttribute(PrintWriter writer) {
            this.writer = writer;
        }

        public void valueBound(HttpSessionBindingEvent event) {
            writer.write("Value bound called");
            writer.write("<br/>");
        }

        public void valueUnbound(HttpSessionBindingEvent event) {
            writer.write("value Unbound called");
            writer.write("<br/>");


}
}




public class SessionBindingServlet extends HttpServlet {

    private static final String SIMPLEATTR = "simpleattribute";

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {

        ServletContext servletContext = getServletContext();            
        PrintWriter out = response.getWriter();
        response.setContentType("text/html");
        try {
            servletContext.removeAttribute(SIMPLEATTR);
            out.write("removed previous attribute successfully");
            out.write("<br/>");
        } catch (Exception e) {

        }

        servletContext.setAttribute(SIMPLEATTR, new SimpleAttribute(out));
        out.write("Added simple attribute successfully");
        out.write("<br/>");
    }
}

2 个答案:

答案 0 :(得分:2)

您实际上并没有将对象绑定到HttpSession,而是将其绑定到ServletContext

您应该使用

检索HttpSession
HttpSession session = request.getSession(true);

并添加属性

session.setAttribute(SIMPLEATTR, new SimpleAttribute(out));

这将触发HttpSessionBindingEvent,它将通知您的HttpSessionBindingListener实现类对象。

答案 1 :(得分:0)

您的代码中存在许多问题:

  • 如果实现接口的对象绑定/未绑定到会话而不是其他对象,则会通知HttpSessionBindingListener。如果需要通过属性set / get on session进行通知,则应实现HttpSessionAttributeListener
  • 您是否在web.xml注册了听众?
  • 最后,HttpSessionAttributeListener会收到有关会话属性更改的通知,而不是servlet-context属性更改,如果您希望实现ServletContextAttributeListener