Category Archives: Httpservletrequest

Saving State in the Servlet Request Object



Introduction

The HTTP protocol wasn’t designed to be statefull. This means that by default it doesn’t remember earlier steps.

The HttpServetRequest Object functions as a kind of coat rack. During the session you can “hang” all kinds of Objects to it, which you can retrieve later on in the Session.

This can be useful, for example when you’re working with a Shopping Cart.

Note that the Request Object is available in both Servlets and JSP’s.

// Save and get a request-scoped value
req.setAttribute("com.mycompany.req-param", "req-value");
Object value = req.getAttribute("com.mycompany.req-param");

// Save and get a session-scoped value
HttpSession session = req.getSession(false);
if (session != null) {
    session.setAttribute("com.mycompany.session-param", "session-value");
    value = session.getAttribute("com.mycompany.session-param");
}

// Save and get an application-scoped value
getServletContext().setAttribute("com.mycompany.app-param", "app-value");
value = getServletContext().getAttribute("com.mycompany.app-param");