Thursday, September 15, 2005

Consider the following:

public class ServletX extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException {
req.getSession().setAttribute("key", new X());
req.getSession().setAttribute("key", new X());
req.getSession().setAttribute("key", "x");
req.getSession().removeAttribute("key");
}
}

and given a Listener class

public class X implements HttpSessionBindingListener {
public void valueBound(HttpSessionBindingEvent event) {
System.out.println("B");
}

public void valueUnbound(HttpSessionBindingEvent event) {
System.out.println("UB");
}
}

Which logging output would be generated by an invocation of the doGet method?
Given answer: BBUBUB
Please explain the output?


req.getSession().setAttribute("key", new X());----->B

req.getSession().setAttribute("key", new X());----->B
Since this line replaces the previous set "key" in the session it will also print UB because the previously set X object is unbound.

req.getSession().setAttribute("key", "x");
This will print UB since the X object is unbound.

req.getSession().removeAttribute("key");
This wont print anything because the String "x" is removed as a result of this method call.

So the output would be BBUBUB.

0 Comments:

Post a Comment

<< Home