Consider the following classes:
public class Dog implements HttpSessionBindingListener,
Serializable {
private
String breed;
public Dog(String breed) {
this.breed = breed;
}
public String getBreed() {
return breed;
}
public void valueBound(HttpSessionBindingEvent event) {
String name = event.getName();
Object value = event.getValue();
System.out.println("Value Bound: " + name + ": " + value);
}
public void valueUnbound(HttpSessionBindingEvent event) {
String name = event.getName();
Object value = event.getValue();
System.out.println("Value Unbound: " + name + ": " + value);
}
public String toString() {
return breed;
}
}
public class BeerAttributeListener implements HttpSessionAttributeListener {
public void attributeAdded(HttpSessionBindingEvent event) {
String name = event.getName();
Object value = event.getValue();
System.out.println("Attribute added: " + name + ": " + value);
}
public void attributeRemoved(HttpSessionBindingEvent event) {
String name = event.getName();
Object value = event.getValue();
System.out.println("Attribute removed: " + name + ": " + value);
}
public void attributeReplaced(HttpSessionBindingEvent event) {
String name = event.getName();
Object value = event.getValue();
System.out.println("Attribute replaced: " + name + ": " + value);
}
}
public class ListenerTester extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("text/html");
HttpSession session = request.getSession();
session.setAttribute("foo", new Dog("Beagle"));
session.setAttribute("foo", new Dog("Great Dane"));
session.setAttribute("foo", new String("z"));
session.removeAttribute("foo");
PrintWriter out = response.getWriter();
out.println("done");
}
}
When the
servlet is called, this is what is logged:
Value Bound: foo: Beagle
Attribute added: foo: Beagle
Value Bound: foo: Great Dane
Value Unbound: foo: null
Attribute replaced: foo: Great Dane
Value Unbound: foo: null
Attribute replaced: foo: Great Dane
Attribute removed: foo: z
My questions:
(1) Why is the "Value Unbound" null in line 4 and 6? Shouldn't they be "Beagle" and "Great Dane" respectively?
(2) Why is "Attribute replaced" in line 5 "Great Dane"? Shouldn't it be "Beagle", which is the value replaced?