我正在阅读关于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")被替换的属性确实会被调用。但名字的价值只剩下彼得。为什么会这样呢?理由是什么呢?另一个问题是我们什么时候特别使用HttpSessionAttributeListener和HttpSessionListener。有什么实际用途吗?
谢谢,彼得
发布于 2012-09-24 19:55:44
因为javadoc说:
返回已添加、删除或替换的属性的值。如果属性被添加(或绑定),这就是属性的值。如果属性被删除(或未绑定),则这是已删除属性的值。如果替换了属性,则这是该属性的旧值。
在第一种情况下,旧值和新值是相同的,所以您可以看到新的狗名。
HttpSessionListener习惯于了解会话的创建和销毁。HttpSessionAttributeListener用于了解会话中的新属性、删除属性和替换属性。他们很不一样。
https://stackoverflow.com/questions/12571298
复制相似问题