0

我正在阅读有关 HttpSessionAttributeListener 的信息,这是我制作的一个小例子。不过我有一个疑问。代码如下

public class TestServlet extends HttpServlet {

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

  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    HttpSession session = request.getSession();
    Dog d = new Dog();
    d.setName("Peter");
    session.setAttribute("test", d);
    /*Dog d1 = new Dog();
    d1.setName("Adam");
    */
    d.setName("Adam");
    session.setAttribute("test",d);
  }

}

这是我的听众课

public class MyAttributeListener implements HttpSessionAttributeListener {
  @Override
  public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
    System.out.println("Attribute Added");
    String attributeName = httpSessionBindingEvent.getName();
    Dog attributeValue = (Dog) httpSessionBindingEvent.getValue();
    System.out.println("Attribute Added:" + attributeName + ":" + attributeValue.getName());

  }

  @Override
  public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
    String attributeName = httpSessionBindingEvent.getName();
    String attributeValue = (String) httpSessionBindingEvent.getValue();
    System.out.println("Attribute removed:" + attributeName + ":" + attributeValue);


  }

  @Override
  public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
    String attributeName = httpSessionBindingEvent.getName();
    Dog attributeValue = (Dog) httpSessionBindingEvent.getValue();
    System.out.println("Attribute replaced:" + attributeName + ":" + attributeValue.getName());

  }
}

这是我的模型

public class Dog  {
  private String name ;

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}

令人困惑的是,当我运行这个程序时,监听器完美地调用了添加和替换的属性。当我取消注释我的 servlet 中的代码并进行注释时

d.setName("Adam")

替换的属性确实被调用。但是 name 的值仍然是 Peter only。这是为什么?什么原因?另一个问题,我们什么时候特别使用 HttpSessionAttributeListener 和 HttpSessionListener。有什么实际用途吗?

谢谢,彼得

4

1 回答 1

1

因为javadoc说:

返回已添加、删除或替换的属性的值。如果属性被添加(或绑定),这是属性的值。如果属性已被移除(或未绑定),则这是已移除属性的值。如果属性被替换,这是属性的旧值。

在第一种情况下,旧值和新值相同,因此您看到了新的狗名。

HttpSessionListener 用于了解会话的创建和销毁。HttpSessionAttributeListener 用于了解会话中新的、删除的和替换的属性。他们非常不同。

于 2012-09-24T19:55:44.207 回答