Hi, I tested by deploying the code and found that the result is
B
B
UB
UB
The reason being,
req.getSession().setAttribute("key",new X()); - This calls ValueBound. So B
req.getSession().setAttribute("key",new X()); - This calls ValueBound. So B
After binding the new value, the old one is unbound. So UB.
req.getSession().setAttribute("key","x"); - This sets the value of key's value to
string x. Then value unbound is called on listener X. so UB.
It can evident from the code, if you modify the code as below.
---------------------------------------------------------------------------
package com.saloon;
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class ServletX extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException{
req.getSession().setAttribute("key",new X("One"));
req.getSession().setAttribute("key",new X("Two"));
System.out.println(req.getSession().getAttribute("key"));
req.getSession().setAttribute("key","x");
System.out.println(req.getSession().getAttribute("key"));
req.getSession().removeAttribute("key");
}
}
--------------------------------------------------------------------------
package com.saloon;
import javax.servlet.http.*;
import javax.servlet.*;
public class X implements HttpSessionBindingListener
{
String s;
public X(String s)
{
this.s=s;
}
public void valueBound(HttpSessionBindingEvent event)
{
System.out.println("B");
}
public void valueUnbound(HttpSessionBindingEvent event)
{
System.out.println("UB");
}
public String toString()
{
return "dog "+s;
}
}
---------------------------------------------------------------------------
B
B
UB
dog Two
UB
x