首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >HttpSessionAttributeListener混淆

HttpSessionAttributeListener混淆
EN

Stack Overflow用户
提问于 2012-09-24 19:10:35
回答 1查看 764关注 0票数 0

我正在阅读关于HttpSessionAttributeListener的文章,下面是我做的一个小例子。不过,我有一个疑问。下面给出了代码

代码语言:javascript
复制
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);
  }

}

这是我的听者课

代码语言:javascript
复制
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());

  }
}

这是我的模型

代码语言:javascript
复制
public class Dog  {
  private String name ;

  public String getName() {
    return name;
  }

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

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

代码语言:javascript
复制
d.setName("Adam")

被替换的属性确实会被调用。但名字的价值只剩下彼得。为什么会这样呢?理由是什么呢?另一个问题是我们什么时候特别使用HttpSessionAttributeListener和HttpSessionListener。有什么实际用途吗?

谢谢,彼得

EN

回答 1

Stack Overflow用户

发布于 2012-09-24 19:55:44

因为javadoc说:

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

在第一种情况下,旧值和新值是相同的,所以您可以看到新的狗名。

HttpSessionListener习惯于了解会话的创建和销毁。HttpSessionAttributeListener用于了解会话中的新属性、删除属性和替换属性。他们很不一样。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12571298

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档