我正在阅读有关 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。有什么实际用途吗?
谢谢,彼得