Easy cookie with EL

When writing a JSP page we have to cope with the fact that there is no getCookie() method in the request object, just a get-all getCookies(). This means that getting just a single cookie is kind of painful. We have to get all of them, and then scan the array of cookie till we find what we are actually looking for.

Good news is that this complexity is hidden when we use the Expression Language.

A servlet creates a cookie:
Cookie cookie =
    new Cookie("accessTime", "time " + System.currentTimeMillis());
response.addCookie(cookie);
In a JSP page we want to get it:
<%
    Cookie[] cookies = request.getCookies();
    for (int i = 0; i < cookies.length; i++) {
        if ((cookies[i].getName()).equals("accessTime")) {
            out.println("My cookie: " + 
                cookies[i].getValue() + "<br />");
        }
    }
%>
Lot of code for such a simple task. Using the EL we can use the implicit object cookie:
<br />Cookie via EL: ${ cookie.accessTime.value}
A good place to read more on the EL-cookie relation is chapter eight of Head First Servlet and JSP.

No comments:

Post a Comment