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>[email protected]</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 params! Had they consulted us, we would have suggested that the spec designers might consider naming this variable, oh, “contextParam”... but once again, they forgot to ask us.

image with no caption

She doesn’t know about EL functions

When you need a little extra help from, say, a Java method, but you don’t want scripting, you can use an EL function. It’s an easy way to write a simple EL expression that calls a static method in a plain old Java class that you write. Whatever the method returns is used in the expression. It does take a tiny bit more work to configure things, but functions give you a lot more...functionality.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset