Attributes' scopes

We can put an attribute in the ServletContext, making it available to all the web app's servlets, or we can put it in the current HttpServletRequest. Moreover, we could put an attribute in the HttpSession.

A reason to choose the ServletContext is that the attribute will be visible by all elements in the Web Application. It could be a good place for a database connection.
An attribute in HttpSession is visible to JSP and servlets in the same session. A shopping cart should be placed here.
Usually just the current servlet and the servlet/JSP to which the current request is dispatched has access to the Request context. Specific info for the current client request should be placed here.

ServletContext and HttpSession are not thread-safe, when required we should a lock on the context, like this:
synchronized(getServletContext()) {
    getServletContext().setAttribute("foo", "22");
    getServletContext().setAttribute("bar", "42");

    out.println(getServletContext().getAttribute("foo"));
    out.println(getServletContext().getAttribute("bar"));
}

// ...

HttpSession session = request.getSession();
synchronized(session) {
    session.setAttribute("foo", "22");
    session.setAttribute("bar", "42");

    out.println(session.getAttribute("foo"));
    out.println(session.getAttribute("bar"));
}
If we didn't syncronize on the ServletContext or on HttpSession, another thread could change the value of an attribute between its setting and its printing.

I originally wrote this post while reading the fifth chapter of Head First Servlet and JSP, a fun ad interesting book on Java EE.

No comments:

Post a Comment