O'Reilly logo

Head First Servlets and JSP, 2nd Edition by Bert Bates, Bryan Basham, Kathy Sierra

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Getting Cookies and init params

We’ve looked at all the implicit objects except cookies and init params, so here we are. And yes, any of the implicit objects can show up on the exam.

Printing the value of the “userName” Cookie

We know we can do it with scripting

<% Cookie[] cookies = request.getCookies();

for (int i = 0; i < cookies.length; i++) {
   if ((cookies[i].getName()).equals("userName")) {
     out.println(cookies[i].getValue());
   }
} %>

Note

This is kind of a pain, because the request object does NOT have a getCookie(cookieName) method! We have to get the whole Cookie array and iterate through it ourselves.

But with EL, we’ve got the Cookie implicit object

${cookie.userName.value}

Note

WAY easier. Just give it the name, and the value comes back from the Map of Cookie names/values.

Printing the value of a context init parameter

We have to configure the parameter in the DD

<context-param>
    <param-name>mainEmail</param-name>
    <param-value>likewecare@wickedlysmart.com</param-value>
</context-param>

Note

Remember. this is how you configure context (app-wide) parameters. These are NOT the same as servlet init params.

We know we can do it with scripting

email is: <%= application.getInitParameter("mainEmail") %>

And with EL, it’s even easier

email is: ${initParam.mainEmail}

Note

The EL initParam is NOT for params configured using <init-param> !

Here’s what’s confusing: servlet init params are configured using <init-param> while context params use <context-param> but the EL implicit “initParam” is for context ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required