Implicit object and scope

Usually we don't specify the scope where an attribute lays, we rely instead on the fact that EL go through all the scopes looking for it - and gets the first one with that name.

But sometimes is good to know that we can use a scope implicit object.

Avoid name conflict

We can't always assume we are choosing, or using, unique names for our attributes, so using the EL scope implicit object could save us some headache.

For instance, referring to the code seen in the previous post, writing
${musicMap.Indie}
has the same result as writing
${requestScope.musicMap.Indie}

"Bad" name for attribute

An attribute name is just a string, we could use almost anything there. But we should use our freedom with a bit a common sense. More to the point, it is not a good idea to call an attribute using the Java class convention. Because, if we create an attribute in this way
request.setAttribute("foo.person", p); // bad attribute name!
we have the unpleasent side-effect we can't access the attribute in a JSP page in this way:
${foo.person.name}
because the containers expects foo being an attribute, and person one of its properties.

The obvious solution would be not to use such kind of names. But there is another solution, thanks to the scope implicit object and the [] operator:
${requestScope["foo.person"].name}
Head First Servlet and JSP is the book I was reading when I firstly wrote this post.

No comments:

Post a Comment