Reputation: 1319
I am trying a HttpSessionBindingListener example and the events are not firing. What am i doing wrong here.
Here is the code for the Attribute class that i am trying to set and the code for the servlet class.
The servlet is working but is not displaying the output that i am expecting.
public class SimpleAttribute implements HttpSessionBindingListener {
PrintWriter writer;
public SimpleAttribute(PrintWriter writer) {
this.writer = writer;
}
public void valueBound(HttpSessionBindingEvent event) {
writer.write("Value bound called");
writer.write("<br/>");
}
public void valueUnbound(HttpSessionBindingEvent event) {
writer.write("value Unbound called");
writer.write("<br/>");
}
}
public class SessionBindingServlet extends HttpServlet {
private static final String SIMPLEATTR = "simpleattribute";
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
ServletContext servletContext = getServletContext();
PrintWriter out = response.getWriter();
response.setContentType("text/html");
try {
servletContext.removeAttribute(SIMPLEATTR);
out.write("removed previous attribute successfully");
out.write("<br/>");
} catch (Exception e) {
}
servletContext.setAttribute(SIMPLEATTR, new SimpleAttribute(out));
out.write("Added simple attribute successfully");
out.write("<br/>");
}
}
Upvotes: 0
Views: 711
Reputation: 7302
There are many issues in your code:
HttpSessionBindingListener
is notified if the object which implements the interface is bound/unbound to session, not other objects. If you need to be informed by attributes set/get on session, you shall implement HttpSessionAttributeListener
.web.xml
?HttpSessionAttributeListener
is get notified on session attribute changes not servlet-context attribute changes, if you want that you shall implement ServletContextAttributeListener
.Upvotes: 0
Reputation: 279890
You haven't actually bound the object to an HttpSession
, you've bound it to the ServletContext
.
You should be retrieving the HttpSession
with
HttpSession session = request.getSession(true);
and adding the attribute
session.setAttribute(SIMPLEATTR, new SimpleAttribute(out));
That will fire an HttpSessionBindingEvent
which will notify your HttpSessionBindingListener
implementing class object.
Upvotes: 2