Showing posts with label jsp. Show all posts
Showing posts with label jsp. Show all posts

Thursday, July 15, 2010

Scriptless JSP Pages: The Power of the Map

One sometimes unexpected side-effect of moving to JSP 2.0 "scriptless pages" is the amount of thought it forces one to focus on the "controller-to-view interface". To me, this side-effect is another major advantage (in addition to the welcome simplification of the pages themselves) to making this transition.

"How on Earth is forcing me to actually think of something an advantage?" you may ask. My answer to that is that more thought to this interface usually means a better interface. And better interfaces equal better program structure. And unless you haven't written a line of code in your life, you know that better program structure equals happier programmers.

Now it's not that there's never been any thought given to this interface before, it's just that in the pre-scriptless era it was common -- because it was just so easy -- for us to code the controller servlet to throw any old data structure onto the request knowing that we could write all the Java we wanted on the page to deal with those structures.

Some of us, and I'll give myself credit to be among those, always had the notion that the less Java on the pages, the better, and gave some amount of thought to gearing the structures passed as request-scoped variables to the needs of the page. But still, because any arbitrary Java code could be included on-page, it wasn't a paramount consideration.

That has all changed. With scriptless JSP pages, where JSP 2.0 Expression Language (EL) expressions are the primary means to reference the scoped variables, adjusting the nature of the scoped variables to suit the pages becomes something to which more thought must be applied.

Over the course of converting a number of my client's web applications to use JSP 2.0 and scriptless pages, I've learned a lot about structuring the controller-to-view data, and one thing that has become apparent to me is the overlooked power of the Map as applied to this problem space.

By "Map", of course I mean implementations of the java.util.Map interface.

Recall that in the Expression Language, the fetch operators (the dot and the square brackets) tailor their semantics to the type of their left operand. In the EL expression:

  ${xyz.abc} 

or the equivalent

  ${xyz['abc']} 

how the EL evaluator determines the value of abc depends upon the type of the value for xyz.

If xyz evaluates to a discrete element, the evaluator attempts to treat abc as a JavaBean property, and to determine its value using the accessor method getAbc().

If however, xyz evaluates to a java.util.Map implementation, the evaluator attempts to resolve the value of abc as the value of the entry with key 'abc'. (Interesting things also happen if xyz is an implementation of java.util.List or an array, but that, as they say, is another show).

This is powerful stuff and opens up the usage of the Map in this context in ways for which we might not previously have thought of using a Map construct.

A Case Study: Member Permissions

One of the web applications that I have updated to use scriptless pages is a community-based recipe sharing site. The app is membership-driven, with each member assigned to a "role" that grants them certain permissions for the various actions that can be performed within the application.

Lowest is the guest role where unregistered visitors can browse the site contents. Registered visitors with the member role can submit recipes to be added to the site contents. Paid members with the gold member role can create private recipe collections and have access to some other advanced features.Moderators can approve submitted recipes, remove member accounts, and perform other policing actions. The most privileged role of administrator can perform all site actions.

Each role is actually a set of discrete permissions that determine what actions visitors possessing that role can initiate. The "add recipe" permission, for example, is granted to all roles but "guest".

Each visitor to the site is identified via an instance of a Member object in that visitor's session. In the JSP 1.x version of the application, a method on this object exposed the permissions that the member was granted based upon the role assigned to that member.

If we imagine a location on the site where an "Add Recipe" button will appear for those visitors that have the "add recipe" permission (which would be all but "guests"), you might have seen JSP code like this:

  <%     Member member = (Member)session.getAttribute( "member" );     if (member.hasPermission( "ADD_RECIPE" )) {   %>          <%     }   %> 

Note: this is a simplification of the actual code. There were ownership considerations that frequently needed to be taken into account, and the strings for the permission names were exported as String constants rather than being hard-coded into the pages. But I'm trying to keep the example code focused on the point to be made.

Converting this to a scriptless equivalent using JSTL tags and the EL might seem straight-forward at first, but when we try to access the "hasPermission" method of the member object, we run into problems.

The EL can easily access properties of objects such as Member, but is unsuitable for calling general-purpose methods, such as hasPermission(), that take parameters.

The means to determine whether a member possesses a particular permission needed to be changed to a mechanism that was "EL-friendly".

One tactic could have been to replace the general purpose method with discrete property accessors. Under this approach each and every permission would need to become a property of Member:

  public boolean getHasPermissionAddRecipe();   public boolean getHasPermissionApproveRecipes();   public boolean getHasPermissionBanMember();   ... 

and so on.

I rejected this approach due to a number of problems. Not only did it not scale well -- as the number of permissions grows, so do the number of accessors necessary -- it artificially makes each individual permission a property of Member. While I had no problem modeling the set of permissions as a property of a Member, making the individual permissions Member properties violated my "OO sensibilities" as it introduced a coupling between the Member object and the available set of permissions. My original model had the Member interface independent from the set of available permissions, and I certainly did not want to gain simplification of the JSP pages at the expense of compromising the model abstraction.

The next thought that occurred to me was to consider using EL functions. Since the problem seemed to be that EL property expressions didn't allow for general function calls, perhaps defining some EL functions would do the trick.

EL functions are means to access static methods defined on a Java class. By creating a static function, perhaps on the Member class itself, I could pass the permission name as a string. But because the method must be static, I'd also need to pass the member object as well.

In a TLD file, such a function could be defined as:

       hasPermission     com.whatever.membership.Member            boolean hasPermission( com.whatever.membership.Member, java.lang.String permission )         

and on-page, its usage would be (assuming that the TLD containing the function was declared and mapped to the prefix 'membership'):

  ... 

Although I liked this solution much better than adding individual properties for the various permissions, I thought that it was a bit wordy on the page, didn't read well at all, and the static nature of the method seemed like a bit of a OO wart on the Member class.

What I really needed was a different means to map the name of a permission to its granted/denied setting.

Light dawned when I finally realized that the solution was in the problem statement itself all along: I needed a means to map the name of a permission to its granted/denied setting.

Thinking back to our previous example of ${xyz.abc}, we saw that not only could abc be a JavaBean property, but it could also be a map key. And one great advantage that a map key has over a JavaBean property, is that it is run-time assignable as opposed to the compile-time hard-coding of accessor methods.

My solution was to create a new property for the Member class that represented the set of permissions granted to that member. I named this property hasPermission and its value is a Map that associates a granted permission name to the value Boolean.TRUE.

Hence, its accessor is:

  public Map getHasPermission(); 

and it can be used on-page thusly:

           

which makes for a beautifully readable EL test expression for the tag.

All it takes is to add the permission names to be tested as a key to the Map -- in our example "ADD_RECIPE" -- with a value that evaluates to true (such as Boolean.TRUE).

Since the expression will evaluate (and without error) to false in the event that the Map lacks a specific key, we need only add granted permissions to the Map. Any denied permissions need not be explicitly added with a value of Boolean.FALSE as the expression will evaluate to false whenever the named entry cannot be found in the Map.

While this does indeed make access from the JSP page very readable, the signature of the accessor is rather odd-looking when used from Java code (permission checking is also performed quite often within the server-side code). But this need not be an issue since nothing prevents us from leaving the originalhasPermission( String permissionName ) method on Member for use within Java code, and leave the new hasPermission property accessor for use solely from EL references.

Note on this example:

Even though the Add Recipe button is hidden on pages displayed to visitors that do not have permission to perform the "add recipe" action, this in no way constitutes adequate security against unauthorized attempts to execute this action. The server-side code for performing this operation (in the business layer of the application) performs its own stringent series of checks to make sure that the requested action is allowed by the visitor's granted permissions.

The point of hiding it on the UI is merely so that visitors without adequate permissions are not presented with a UI element that will result in a "permission denied" error upon its usage.

Another Case Study: Constants

A recent post in the JSP Forum of the JavaRanch Big Moose Saloon brought up another interesting case study.

In the post, the author -- another firm believer in the "goodness and light" of scriptless JSP pages -- lamented the fact that without scriptlets or scriptlet expressions, it was impossible to reference static constants defined in Java classes. Indeed, using the facilities of the Expression Language, this is not possible.

Such references proved quite useful in pre-scriptless applications. Take for example, a common bug introduced by a simple typo naming a form element on a JSP page. Let's say that in servlet SomeServletto which a form on a page is to be submitted expects a request parameter named "description":

  String description = request.getParameter( "description" ); 

But on the page, the form element is coded as:

   

This error causes the request parameter value in the servlet to always be null since no form element with the expected name actually exists. This type of bug is easy enough to fix, but can waste a great deal of time trying to find.

By using a string constant defined on the servlet (or in some other abstraction as we will discuss later):

  public static final String KEY_DESCRIPTION = "description"; 

this type of bug can be avoided by using the constant in the servlet itself:

  String description = request.getParameter( KEY_DESCRIPTION ); 

and within the JSP as:

  "/> 

assuming that SomeServlet has been imported into the JSP.

While this may be somewhat notationally heavy, it has the distinct advantage of generating a compile-time error should any typo in the key reference be made.

Within a JSP 2.0 scriptless page, such scriptlet expressions are not possible. And while even the power of the Map cannot achieve the invaluable utility of a compile-time check, it can be used to make such errors at least a little easier to spot.

Let's take the well-known example of a simple login form which consists of two entry fields: a username and a password. Knowing that simple string constants exported from a servlet, or any other class for that matter, will have no utility for our scriptless JSP pages, we'd like to use a Map to create references that can be readily and readably used on the JSP pages.

Since we're going to be exporting more information about the form and its elements than a simple set of string constants, it makes sense to formalize an abstraction of our "form" and its elements, decoupling it from any one specific servlet (or page).

In this abstraction we'd like to export information that is usable from any servlet that deals with our "login form", as well as from the JSP page that will implement the UI elements that present the login form to the user.

Here's how it might be done:

  public class LoginForm {     public static final String KEY_USERNAME = "username";     public static final String KEY_PASSWORD = "password";     public static final Map FORM_KEYS = new HashMap();     static {       FORM_KEYS.put( "KEY_PASSWORD", KEY_PASSWORD );       FORM_KEYS.put( "KEY_USERNAME", KEY_USERNAME );     }   } 

In this class the form keys are exported as string constants that are easily used by any Java code (particularly servlets) that need to reference them.

A Map of the form element keys whose keys are named using the conventional naming format for constants is also exported. When placed onto request scope by code such as:

  request.setAttribute( "FormKeys", LoginForm.FORM_KEYS ); 

the form elements in the scriptless pages can now be coded as:

      

Because of the names and naming conventions we used to create the Map and the scoped variable, the purpose of the references is immediately recognizable as mimicking constant values.

Note: it could be argued that even though the spirit of these references is to be used as constant values, that, since they are not, they should not be named like constant references. I'll leave such philosophical discussions for another time.

Operationally, if the FormKeys scoped variable does not exist or if the key name is mis-typed, no error is thrown, but blank output is rendered.

While this is nowhere near as useful as having a compile-time (or even run-time) error thrown that reaches out and slaps you in the face, a typo in the JSP page now results in a pattern that should be easier to spot by inspection, as well for which automated searches can be created. If, for example, the following error is made:

   

the resulting rendered HTML would be:

   

which would be easier to spot in the rendered page than a hard-coded typo like:

   

and for which it is easy to create an automated search that finds instances of the name attribute with an empty value.

Whether it is worth all this setup for what some might think is marginal gain is up to the individual to decide. I include it here as another example of how a Map can be used in conjunction with JSP scriptless pages in ways that might not be obvious.

However, I will assert that the utility of creating a "form abstraction" as described here is more far-reaching than this example. Imagine that such a class was extended to be able to fetch its known parameters given a request instance, could convert the parameter values from strings to integers, dates or other non-string types as appropriate, and perhaps even perform simple, context-free validations on its elements. This would be a powerful abstraction that not only collects the form elements into a cohesive entity, but decouples the concepts of the "form" from the servlets (or other items) that reference it.

The utility of such an abstraction might not seem evident when thinking of our simple login form that possesses two simple string fields. But imagine a more complex form; say, the myriad fields of various types that go into selling an item on eBay®. Collecting all this information into an abstracted instance could significantly simplify the code that needs to deal with it.

Summary

In this article, we've looked at a number of ways to use the Map interface in conjunctions with JSP scriptless pages. Because Map keys can be referenced in an Expression Language expression as if they were properties, the Map provides a clever way to create "property names" that are not, or cannot, be known at compile time in a way that is not possible with formal JavaBean properties.

The Secret Life of JavaServer Pages

"How do I call a bean method from a Javascript onclick handler?"
"When I write to a file in my JSP, why does it appear on the server? I want to write to the client system!"
"Why does everyone tell me to use a servlet to send binary data to the browser? I wanna use a JSP!"

To those that frequent the JSP Forum of the JavaRanch Big Moose Saloon, these questions may appear hauntingly familiar as they are among some of the most recurring questions asked by new-comers to the Ranch and to JSP.

While these questions may seem somewhat unrelated to each other, they all have a similar root: a fundamental misconception of what JavaServer Pages (JSP) technology is, and of the life-cycle of a JSP page.

In this article, I hope to clarify what JSP is, how JSP pages work, and how understanding their life-cycle clears up the answers to questions such as those above, and many more.

What's it all about, Jasper?

One thing that JSP technology is not is a means to cause Java code to be executed as part of a web page on the client-side browser. That's what Applets are for.

It is also not a means to deploy stand-alone Java applications to a client system for local execution; that's the job of Java Web Start.

So what is JSP Technology?

Stripped down to its very core: JSP is a templating technology used to dynamically generate content for delivery to a client, usually a browser.

...

Hello?

Ohhhh-kay... let's try that again...

The Two County Clerks

A traditional web server actually has a pretty simple job. When a request (in the guise of an HTTP request) is made for a particular resource (most often an HTML page or image file), the web server responds (in the guise of an HTTP response) by reading the bytes of the requested resource and feeding them across the net to the requesting browser. Whatever is in the file is what gets delivered.

A templating engine on the other hand, uses the information in the requested resource, combined with data that it can garner from various resources, to dynamically generate the content to be delivered.

To illustrate this difference, let's imagine that you need to visit your local county tax office in order to straighten out what you think may be an error on your yearly property tax bill. In order to research the issue, you determine that you need two documents:

  1. The County Tax Rules Document
  2. The Property Assessment Document for your property

So you arrive at the Tax Office and determine which clerk to go to in order to obtain the County Tax Rules Document. You queue up into line, and when it comes your turn, you request a copy of the County Tax Rules Document.

The clerk responds by turning to his file cabinet stuffed with documents, retrieves one of those documents, places it on his copy machine, and hands you the results of the copy operation.

You walk away with a static document in your hands. The document is an identical copy of the document that was in the clerk's file cabinet with no interpretation. If you were to go back and ask for the document again, you would receive a copy exactly like the one that you just obtained. Anyone else who requests a copy of the document also receives a copy that is identical to the one that you have in your hands.

This first clerk operates in much the same manner as a traditional web server. Its primary job is to send, verbatim, the contents of a specific file on the server to the client upon request.

To obtain the second document — the Property Assessment document for your property — you visit another clerk. This clerk is a more capable worker, able to handle the complexities of creating a document for you that is more than a simple copy of an existing document; one that is customized with information specific to you (or as in this case, your property).

When your turn comes, you request a copy of a Property Assessment document for your property. Unlike, the previous document that you requested, this document requires that you also provide a means of uniquely identifying the property for which the document is to contain the assessment information. In this case, the uniquely identifying piece of information is the address of the property.

In response to your request, the clerk fetches a document from her file cabinet — much in the same manner that the first clerk did — but does not hand a copy of it directly to you. Rather, she also turns to another file cabinet and looks up the information specific to your property and lays it out on her desk.

She then makes a copy of the Property Assessment document that she fetched, and places it into her typewriter. As she does so you see that this is a document that is only partially filled in. It has lots of writing already on it — labels, lines, and other markings — but also contains lots of blanks where property-specific information should be. With deft fingers, and using the property information she retrieved for your specific property, she fills in those blanks with the appropriate data. For some of this information she turns to her calculator to compute the appropriate values to fill in using the information available to her.

When she is finished, she pulls the document from her typewriter and hands it to you. You walk away with adynamic document in your hands.

This document differs from your first, static document in that it is tailored with information that is specific to your property. If you, or anyone else, were to request the exact same document, but supplied a different property address, the document's content would be different; tailored to the information appropriate for the property identified by the supplied address.

This second clerk operates in a similar fashion to the way that a templating engine such as a JSP container would operate. She generated a document tailored with specific data by starting with a source template and filling in information specific to a particular element in her "database". Similarly, a JSP container will take a source template, a JSP page, and using JSP markup within that page generate a dynamic document tailored with specific information.

So why would we want to use such templating technology when traditional web serving is so much more simple and straight-forward? Well, let's revisit the Tax Office...

A frugal, but uninsightful, taxpayer might argue that the County is wasting tax dollars by operating in this fashion. After all, would it not be cheaper, not to mention faster, just to have a low-level clerk simply look up and hand you a Property Assessment document already filled with your property's information? Could they not save salary dollars by hiring less-capable clerks who only have to know how to use a copy machine rather than a much more complicated typewriter?

Of course, the answer is no. If the Tax Office were to attempt to operate in that fashion, then they would need to have a pre-filled Property Assessment document for each and every property in the county. And what about other documents which are also property-specific? Not only would the Tax Office need to hire a whole gaggle of clerks to create those documents in the first place, they would also need to store those documents causing them to incur rental costs for the enormous amount of space that would be necessary.

And what about when the information on the various properties changes? Each change would mean throwing away all of the pre-created documents and typing them in all over again. Expensive, inefficient and wasteful!

So with even a cursory examination, we see that the Tax Office is making good use of our tax dollars by storing one template for each document type, and filling that template in with up-to-date information at the time that the document is requested.

This is why technologies such as JSP make so much sense. By creating dynamic documents on-the-fly with real-time data, there is no need to anticipate and store every possible document variation that might ever be requested, and the information in those documents can always be kept up-to-date by simply keeping a singleinstance of the data current.

Anatomy of a JSP

Like the fill-in-the-blanks form of our plucky county clerk, a JSP page is a template for creating the end document. The template contains both static and dynamic elements. The static elements are copied verbatim to become part of the document, while the dynamic elements are interpreted at request time in order to "fill in the blanks" with appropriate data.

Let's take a look at a simple JSP page, with highlighting to point out the various types of elements:

 1   2   3   4     5       6     7   8     9    Testing   10  
    11      ${n}   12      13    !  14    15      

The background colors in this code example are keyed as follows:

line numbersThese numbers at the beginning of the lines are not part of the JSP file, but are shown in this example so that we can easily refer to specific parts of the example in the remaining sections.
dynamic elements

Dynamic elements are markup elements that tell the JSP engine how to interpret the page and what actions to take in order to "fill in the blanks" with dynamic data.

Dynamic elements use varying notation depending upon what category of action they represent. Only a small handful of these dynamic markup types are represented in this simple JSP example1.

template text
"invisible" template text

Characters which are not part of a dynamic element within a JSP are considered part of the final document and will become part of the document exactly as written in the JSP file. These static elements are collectively termed template text.

Note that even the "invisible" line terminators at the end of each line are considered template text and will become part of the final document; even when the rest of the line is empty or composed entirely of dynamic elements.

1 This article is most emphatically not meant to be a tutorial on JSP and all its capabilities. That would take a very long article indeed. In fact, that's why entire books are devoted to this subject. The facets of JSP discussed within this article extend to only those needed to illustrate the concepts being addressed.

Looking at this example we see that, except for dynamic elements on lines 1, 10, 11 and 12, that the page consists mostly of template text. This is typical of many JSP pages.

All of that template text will be sent, verbatim, to the final document (line breaks included), while the dynamic elements will be interpreted.

On line 1, we see a dynamic element that is an example of a JSP directive. This particular directive instructs the JSP engine to find a custom action library2 using the specified URI, and to load it for the scope of the page using the XML namespace of c. This element produces no output to the final document.

2 You may be more accustomed to the term tag rather than action in this context, but as of the JSP 2.0 specification, what was formerly known as standard and custom tags are now termed the standard and custom actions. A perhaps unfortunate naming collision as many web application frameworks, such as Struts, use the term "action" to mean a unit of execution.

On lines 10 and 12 we see a custom action from that library in use. The library in this example is the JSTL set of core actions, and the action employed is the forEach action which causes its body to be iterated over based upon its attribute settings. This element also causes no output in the final document.

On line 11 we see another dynamic element, in this case an Expression Language (EL) expression which causes its evaluated value to be emitted to the final document.

Visiting this page (when hosted on an appropriate JSP 2.0 server) results in the following simple display:

While that's not very impressive or even interesting, what is interesting is examining the final document as sent to the browser. Viewing the source of the response document shows us the specific text of the final document as it was sent to the browser. (This, by the way, is the first debugging step you should take when a JSP is not producing the output you expected when displayed in a browser. Examining the rendered HTML document can usually quickly tell you whether the problem lies in your HTML formatting or elsewhere).

Performing a 'View Source' in the browser shows us:

 1   2   3   4     5      6     7   8     9    Testing   10  
    11      1   12      13      2   14      15  
    3   16      17    !  18    19    

There are a number of intriguing details to note about this final document. Firstly we can see that all of the template text has been dutifully reproduced in this final document. We can also see that none of the dynamic elements remain. Those elements were interpreted on the server and were not written to the final document. And we can see that the EL expression element from line 11 of our JSP template caused dynamic data, in this case the numerals 1, 2 and 3, to be placed into the final document.

Also interesting to note is that all of the template text, including the line terminators, has made its way into the final document (resulting in a lot of the "blank lines" that are seen in that document). This is one of the reasons that JSP is a rather unsuitable technology for delivering anything but text content to the browser.

JSP technology was designed as a templating mechanism for text content, not binary content. Its underlying mechanisms assume that the document begin created is text, and details such as the dutiful emission of all template text including leading and trailing spaces, as well as line terminators makes JSP a problematic technology for delivering content whose structure would be corrupted by the addition of these template characters.

Moreover, there are even types of text documents that are not well-suited to JSP. RTF (Rich Text Format) is a good example. RTF is very sensitive to the placement of line terminators and white-space characters. Put one in the wrong place, and "poof!", your formatting goes right out the window!

Therefore, JSP's suitability is not only limited to the generation of text documents, but to text documents of a format that is at least fairly insensitive to the placement of white-space (including line terminators). This makes JSP best-suited for documents in HTML and XML formats, where interstitial white-space is relatively meaningless.

OK, that's all well and good. But how did all that magic happen "under the hood"? The next section takes us through a day in the life of a JSP page. Assuming that by "day", we mean a request-response cycle.

The Life and Times of a JSP

As we have seen, a JSP page is merely a text file containing elements, both static and dynamic, that define a template for a document. When a request for that document is made, the JSP engine interprets the JSP template and formats an HTML document that gets sent to the browser. How does it do that?

In a nutshell, the JSP Engine turns your JSP template into a servlet. Whenever you request the document represented by the JSP, the engine runs that generated servlet in order to create the HTML document to be sent to the browser.

But let's take a little bit of a closer look at the steps that need to be taken in order to make that happen.

Let's assume that we have just written the simple sample JSP page from the previous section. We place it on the server in a place accessible to the JSP engine (web application setup is beyond the scope of this article; see the documentation for your JSP container), and enter the appropriate URL that references the JSP page.

The JSP Engine receives the request for the JSP page and first checks to see if the JSP has been referenced before. If not, it needs to pass the JSP through a translation phase. This is the phase in which the text of your JSP page is parsed, and a servlet is generated on behalf of the JSP. Most containers will actually generate a text .java file and place it in the file system of the server. This java file is compiled and the resulting servlet class, also usually written to disk, is loaded by the engine's class loader and is registered as a servlet in the enclosing web application.

The first time that your JSP is requested, obviously the translation phase will not have occurred, and so the translation phase will be triggered. However, the translation phase will also be automatically triggered if the JSP has been changed since the last time it was translated.

In either case, the result is a servlet class, loaded and ready to run in the execution phase.

In the execution phase, the servlet is executed by calling its service method which results in executing the code that the JSP engine generated on behalf of your JSP. This results in "writing" an HTML document which is then sent to the browser.

When next the JSP is requested, the JSP engine merely needs to execute the JSP's servlet for each request (assuming that the JSP has not been changed in the meantime).

The following diagram shows a simplified overview of this process:

Armed with this knowledge, let's go back and re-examine the questions posed at the beginning of this article. The answers should now be readily apparent and understandable.

"How do I call a bean method from a Javascript onclick handler?"

Obviously, you can't. As we have seen, the JSP executes on the server (or rather, the JSP's servlet executes) and formats an HTML document that is sent to the browser. The browser, which then interprets the HTML and any Javascript in the document (which, from the point of view of the JSP engine is just template text along with the rest of the HTML markup) is completely unaware that the document it has received was generated via a dynamic mechanism.

It's as if the second clerk of our Tax Office analogy operated behind an opaque screen. You asked for a document, and you got handed one that contains the information you requested. Whether the clerk merely made a copy of a static document, used her typewriter to fill in the blanks (putting aside visual differences that could clue you in), or pulled the document out of a magic top hat, is a mystery to you. All you know is that you have the document you requested, and any further interaction with the clerk would have to be in the form of another document request.

"When I write to a file in my JSP, why does it appear on the server? I want to write to the client system!"

This is an easy one. We know that the servlet generated on behalf of the JSP executes on the server. So any file operations performed by that servlet will take place on the server's file system.

"Why does everyone tell me to use a servlet to send binary data to the browser? I wanna use a JSP!"

Since we know that the JSP engine expects to be generating text data (the underlying input/output mechanisms are text-oriented) and that all template text in a JSP including white-space is emitted as part of the document, we can see that using a JSP to emit binary data (or even strictly formatted text data) whose structure would be corrupted by such extraneous characters is a rather foolish thing to try to do.

A JSP Exposed!

Before we close, let's take some of the clothes off of our sample JSP and take a small peek at its innards to help illustrate some of the previous points.

The following code sample is the portion of the servlet generated on behalf of our sample JSP that emits the majority of the output for the document: (examining the entire servlet source code is beyond the scope of this article and would be very container-specific — the code sample shown here was generated by Tomcat 5.0.28)

      out = pageContext.getOut();       _jspx_out = out;        out.write("\r\n");    
   out.write("\r\n");    
   out.write("\r\n");      
 out.write("  \r\n");    
   out.write("    \r\n");     
  out.write("  \r\n");   
    out.write("\r\n");    
   out.write("  \r\n");    
   out.write("    Testing \r\n");   
    out.write("    ");      
 if (_jspx_meth_c_forEach_0(_jspx_page_context)) 
        return;    
   out.write("\r\n");    
   out.write("    !\r\n");   
    out.write("  \r\n");    
   out.write("\r\n");   
    out.write("\r\n");   

Note how the template text ends up begin defined within string literals, and that all of the template text, line terminators and all, is dutifully emitted.

Summary

So what have we learned? Hopefully, at least that:

  • JSP is a templating technology best-suited to the delivery of dynamic text documents in a format that is white-space agnostic.
  • Template text within a JSP page (which is anything that is not a dynamic element), to include all white-space and line terminators, becomes part of the final document.
  • All dynamic elements in a JSP are interpreted on the server and once the document is sent to the client, no further dynamic interaction is possible (short of requesting the same or another document).

Peace out.

Scriptless JSP Pages: The Constant Constants Consternation

I've heard it again and again and again: "I love writing scriptless JSP pages using the JSTL and EL, butdang, why isn't there a way to reference constants in the EL?!?!"

This constant consternation regarding constants is a refrain that resonates strongly with me. When I first started writing JSP pages without scriptlets and scriptlet expressions, the inability to easily referenceclass constants was a sorely missed capability.

In this article, the term class constant is used to mean a class field with the modifiers public, static and final.

I even flirted with cheating a little by using scriptlet expressions to reference class constants in otherwise scriptless pages. This dalliance didn't last very long as not only did it violate my sense of architectural integrity, it broke down in places where scriptless body content must be maintained (for example: within tag files and within the bodies of custom actions based on SimpleTag).

One particular area in which I felt the pain most intensely was in the naming of the form elements within an HTML

to be submitted to my action servlets...

The Form Element Names Example

In my web applications, I dislike repeating literal string values in more than one place. Heck, that applies to any literal values — not just strings. Few would argue that this is not a good practice to follow.

I also usually employ a pattern in which the aggregate collection of data submitted as part of a request is abstracted into a class that understands how to deal with that data. These classes are responsible for collecting the data from the request parameters, performing any conversions from string data to other formats (integers, dates and so on), performing simple context-free validations, and in general, making it easy for the action servlets to interact with the submitted data on an abstracted level. This pattern, which I unimaginatively call a Form, should be familiar to users of Struts or similar web application frameworks that employ comparable abstractions.

Within these "Form" classes I define a series of class constants that represent the names of the form elements. Additionally, these constants serve as the keys in a map of the submitted form data that the class represents. As an example, for a typical "login form", you might see:

package org.bibeault.jrjournal.ccc.test;  public class LoginForm implements Form 
{ 1     public static final String KEY_USERNAME = "username";
 2    public static final String KEY_PASSWORD = "password";     ...     

1 The LoginForm class is declared. The Form interface being implemented is defined by the light-weight framework that I employ and will not be further discussed as it is not particularly relevant to this discussion.

2 For each named form element, a class constant is declared that represents a string literal containing the name of the element. In this example, our form is a simple one; defining only two elements.

In this way, the string literals that represent the form element names are defined once as class constants and then referenced throughout the application using compile-time class constant references. This prevents simple typos in the names of the form elements from turning into hard-to-find run-time bugs. Rather, a typo in the referenced constant name induces a compile-time error that is easy to find and fix quickly.

Prior to the advent of scriptless pages, you might have found the following form elements on a JSP page employing the defined LoginForm to create an HTML login form (within an appropriate tag, of course):

Username: "/>
Password: "/>

Because compile-time class constants are being referenced (rather than hard-coding the names of the elements) bothersome run-time bugs that might be introduced by mistyping the element names are avoided. For example, mistyping the hard-coded element name as "usrename" would result in a run-time bug (in which a call to getParameter() on the servlet request using the correct name would always result in a null value). By contrast, mistyping the class constant reference as LoginForm.KEY_USRENAME would result in a loud and obnoxious — but quick and easy-to-fix — compile-time error when the page is translated.

But within a scriptless page we're rather sunk. Because the JSP EL (Expression Language) makes no provisions for accessing class constant values, we have no means to easily replace the scriptlet expressions that reference the class constants representing the element names with scriptless EL expressions.

Wouldn't it be nice to be able to use something like:

Username: ${LoginForm.KEY_USERNAME}"/>
Password: ${LoginForm.KEY_PASSWORD}"/>

But we know that the EL makes no such provisions for referencing class constants in this or any other direct manner.

What to do? What to do? We want to avoid resorting to scriptlets, but we also want to do something better than falling back to hard-coded string literals in the JSP pages. What to do?

Reflection to the Rescue!

As the EL does not provide any mechanism to allow class constant references on the pages, we'll use some "Java voodoo" to do it ourselves! And the voodoo of which I speak is none other than Java reflection: one of the handiest tools in our Java toolbox.

Regardless of what we decide to do on-page, we're going to need a means to look up the value of a class constant given its fully qualified name. To use an example from our previous discussion, we'd like to be able to use a string such as org.bibeault.jrjournal.ccc.test.LoginForm.KEY_USERNAME to lookup its value "username".

Since we'd probably like to reference such a mechanism from multiple places (and because abstraction is just such a wonderful thing in its own right) we'll create a "class constant inspector" class to look up and obtain the value of a class constant given its fully qualified name (which I refer to within this article as its "path").

We will then be able to use this "inspector" in various ways that may suit our needs within the web application.

The ClassConstantInspector Class

The full implementation of the ClassConstantInspector class is available in the jar file accompanying this article (see the Resources section), but we will examine the "meaty" parts here.

Using this "inspector" class is quite simple: an instance is constructed supplying the path to the class constant, then the instance can be queried for the value of the constant.

The constructor for the class does the lion's share of the work:

public ClassConstantInspector( String constantPath )
 1     throws ClassNotFoundException, NoSuchFieldException {   
  FieldPathParser parser = new FieldPathParser( constantPath );
 2     this.field = Class.forName( parser.getDeclaringClassName() )    
                  .getField( parser.getFieldName() );
 3     if (!Modifier.isPublic( this.field.getModifiers() ) || 
4         !Modifier.isStatic( this.field.getModifiers() ) ||   
      !Modifier.isFinal( this.field.getModifiers() ) ) {  
       throw new IllegalArgumentException( "Field " + constantPath +                        
                     " is not a public static final field" );     } }     

1 The constructor is called with the path to the class constant to be inspected; for example, the string "org.bibeault.jrjournal.ccc.test.LoginForm.KEY_USERNAME".

2 The passed path name is broken down into its class name and field name ("org.bibeault.jrjournal.ccc.test.LoginForm" and "KEY_USERNAME" respectively) using theFieldPathParser class. This latter class simply breaks the passed string into its component parts and will not be further discussed in this article. An implementation using a regular expression to perform the parsing is provided in the ccc.jar file referenced in the Resources section.

3 The java.lang.reflect.Field instance describing the target field is obtained and stored in an instance variable.

4 The field is checked to make sure that it is a "class constant"; that is, a public, static andfinal field. If not, an IllegalArgumentException is thrown.

After construction, the value of the field can be queried by calling the getValue method:

public Object getValue() throws IllegalAccessException, InstantiationException { 
    return this.field.get( null ); 1 }     

1 The value of the field is obtained using the get() method of Field. Note that since the field is static (as enforced by the constructor check), null is passed as the parameter. For non-static fields, this parameter would be an instance of the containing object to query.

As a convenience, a static function that can be used to query for a class constant value is also included:

public static Object getValue( String constantName )     
throws NoSuchFieldException, ClassNotFoundException,      
      IllegalAccessException, InstantiationException {
     return new ClassConstantInspector( constantName ).getValue(); }     

With that under our belt, let's explore how we can exploit this mechanism to ease our constant constants consternation in scriptless JSP pages.

The Custom Action

When enhancing the capabilities of a JSP page, the custom action mechanism is frequently one of the first means considered.

Custom actions may be better known to you as "custom tags". As of the JSP 2.0 Specification, the term action is used rather than "tag" to described the standard and custom tag mechanisms.

One of the first directions we might consider when defining a custom action that uses our new class constant inspector is one that looks up and emits the value of the constant given its path. This would be very much like the JSTL action except that the tag would emit the value of a class constant rather the evaluation of the value attribute.

We can certainly define such an action using the tools at our disposal. But upon a few moments of reflection (no pun intended) we can determine that such a tag would have some severe limitations; the primary of which would be that, since it is a custom action, it could not be used in contexts where custom actions are disallowed: attributes of other actions, for example.

Rather, we will pattern our class constant custom action on the JSTL tag whose purpose is to evaluate a value and create a scoped variable that represents that value. Such scoped variables can then be used in contexts where custom actions cannot; most interestingly, within EL expressions which can be used liberally within a JSP page, including within the attributes of standard and custom actions.

The TLD entry for our custom action (with the elements removed for brevity) is:

     setConstant     org.bibeault.jrjournal.ccc.SetConstantTag     empty  
            constant         true         true                   var    
     true         false                   scope         false      
   false           

The ccc.tld file for the code examples in this article is available in the accompanying jar file referenced in theResources section).

Its resemblance to the JSTL action is readily apparent, with the constant attribute specifying the class constant path replacing 's value attribute (which is usually used to specify an EL expression to be evaluated).

The implementation of this tag is surprisingly straightforward:

public class SetConstantTag extends SimpleTagSupport {   
   private String fieldName;     private String varName;   
  private String scopeName;     
 public void setConstant( String value )
 { this.fieldName = value; }    
 public void setVar( String value ) { this.varName = value; }
     public void setScope( String value ) { this.scopeName = value; } 
     public void doTag() throws JspException {        
 try {         
  ScopedContext scopedContext = (this.scopeName == null) ?   
            ScopedContext.PAGE : ScopedContext.getInstance( this.scopeName );
  1           Object constantValue =      
         ClassConstantInspector.getValue( this.fieldName );
 2  getJspContext().setAttribute( this.varName,   constantValue, 
scopedContext.getValue() ); 
3         }         catch (Exception e) {      
       throw new JspException( "Exception setting constant " +    
  
  this.fieldName, e );
 4         }     } }     

1 The scoped context name (one of: page, request, session or application) is used to look up the instance of the ScopedContext type-safe enumeration that describes the named context. This abstraction associates the scoped context names with the integer values expected by thePageContext class. Its implementation is available in the ccc.jar file.

2 The ClassConstantInspector class is used to lookup the value of the specified class constant.

3 The scoped variable is created using the specified var name and scope.

4 Any exception throw during the tag processing is re-thrown as the root cause of a JspException.

Applying this new custom action to the "login form" example discussed earlier might look something like:

  ...  org.bibeault.jrjournal.ccc.test.LoginForm.KEY_USERNAME"        


  var="usernameKey"/> org.bibeault.jrjournal.ccc.test.LoginForm.KEY_PASSWORD"  
  var="passwordKey"/>  ...  
Username: ${usernameKey}"/>
Password: ${passwordKey}"/>

With this custom action, we have established a means to reference class constants on our JSP pages without resorting to scriptlets or scriptlet expressions. This represents a huge step forward over hard-coding the literals values in scriptless contexts.

But... (isn't there always a "but"?)

This mechanism is not without issues. Foremostly, it violates my architectural sensibilities in that we now have two variations of actions to create scoped variables: for values derived from EL expressions, and for values derived from class constants. Would it not be completely awesome if we could figure out some way to achieve the same ends using just ?

But how?

The value of the value attribute of the action can contain any EL expression, but we've already established that EL expressions cannot reference class constants. So how could we possibly piggy-back on using our class constant inspection mechanism?

Well, the EL may not be able to access class constants but, as of JSP 2.0, it can access static functions via the EL function mechanism. Where can we go with that?

The ccc:constantValue EL Function

As of JSP 2.0, functions that can be called from within EL expressions can be mapped to static methods of Java classes. See section JSP.2.6 of the JSP 2.0 Specification for details.

Magically — well, by design — we already have a static method that we created in theClassConstantInspector class that we can leverage for this very purpose. By adding the following entry in the TLD file:

   constantValue   org.bibeault.jrjournal.ccc.ClassConstantInspector      
  java.lang.Object getValue( java.lang.String )         

we can enable access to the ClassConstantInspector.getValue() static method from within EL expressions.

So now, in our JSP page, we can use to create scoped variables with the values of class constants.

Applying this to our login form example, we get:

  ...  ccc:constantValue('org.bibeault.jrjournal.ccc.test.LoginForm.KEY_USERNAME')}
"/>
 ccc:constantValue('org.bibeault.jrjournal.ccc.test.LoginForm.KEY_PASSWORD')}"/> 
 ...  
Username: ${usernameKey}"/>
Password: ${passwordKey}"/>

This is getting better and better! We can now assign the value of class constants to scoped variables using the standard JSTL action rather than resorting to creating our own non-standard action to do so.

With this EL function we could also forgo the scoped variables entirely, using the function directly in thename attributes of the form elements if you don't mind the wordiness of the function reference.

But (there's that "but" again), since we are hyper-critical perfectionists (well, at least I am), we examine our creation with a discerning eye. And when we do, we identify some limitations:

  1. The EL function mechanism is only available for JSP 2.0 containers. And while the time has come for everyone to migrate to JSP 2.0 if possible, engineering realities dictate that some people may still need to function in a JSP 1.2 world for the time being.

    The custom action we defined in the previous section can be retro-fitted to function in a pre-JSP 2.0 environment if re-implemented using classic tag handling support.

  2. This mechanism, cool as it may be, may not scale all that well. This EL function mechanism (as well as the custom action we defined in the previous section) requires us to either create a scoped variable for each and every class constant that we wish to reference within the JSP page, or use some pretty long and gnarly-looking notation directly in the markup.
  3. The EL function mechanism itself could be viewed as "notationally messy". Call me a neat-nik.

So, as powerful as this mechanism is, it may not be a perfect fit for all situations. Can we come up with even more "magic" using our class constant inspection voodoo?

The Power (and Possible Perversion) of the Map

In a previous JavaRanch Journal article we discussed the "Power of the Map" as it relates to the EL. In that article, we discovered that the java.util.Map interface was a mighty tool for referencing properties in a dynamic fashion. Could this flexibility also help us ease our constant constants consternation?

Recall that in an EL expression such as ${abc.xyz} — which is a short-hand notation for ${abc['xyz']} — if the scoped variable abc implements java.util.Map then the value of the EL expression is the value for the mapped key "xyz".

Can that help us? In the "Power of the Map" article we discussed having the servlet controller construct a Map of all the constants we'd need that we can send to the page as a request-scoped variable, but can we simplify that?

What if, rather than using a HashMap (or other pre-defined implementations of java.util.Map), we created our own implementation of java.util.Map that could look up the value of a key on the fly? Would that be incredibly clever, or would it be a heinous perversion of all that is good? Or both?

The ClassConstantMapper Class

Considering that the get() method of java.util.Map is the only method of interest when accessing Map entries via the EL, let's define a class that implements that interface:

public class ClassConstantMapper implements java.util.Map {     

and declare the get() method required by the java.util.Map interface as follows:

public Object get( Object key ) {
 1     try {         return ClassConstantInspector.getValue( key.toString() ); 
2     }     catch (Exception e) {   
      throw new IllegalArgumentException( "Error looking up value of constant " +      
                                       key.toString() + ": " + e.getMessage() );     } }  
   

1 When an instance of this class is used as a scoped variable, any references to a property of this variable will cause the get() method to be invoked with the property name as the key parameter.

2 The services of the ClassConstantInspector are used to determine the value of the class constant specified by the passed key and is returned as the value.

Since the other methods defined by the java.util.Map interface are either of no interest, or have no real meaning in this context (what would we return for the entrySet() method? A Set of all class constants for all the classes in the class path? Absurd!), we throw an UnsupportedOperationException for every method except get(). For example:

    public Set entrySet() { throw new UnsupportedOperationException(); }     

We also need a means to establish a scoped variable of this class so that we can reference it on the pages. We could simply expect that the servlet controller would set it up for the page, or we could define a new custom action that would do it for us on the page itself. But, since our class has a no-args constructor, we could simply employ the services of the standard action to establish a scoped variable using an id of our choice.

So our login form example becomes:

id="constants" class="org.bibeault.jrjournal.ccc.ClassConstantMapper"/>  ...  
Username:

constants['org.bibeault.jrjournal.ccc.test.LoginForm.KEY_USERNAME']}"/>
Password:

constants['org.bibeault.jrjournal.ccc.test.LoginForm.KEY_PASSWORD']}"/>

Note that with this mechanism, the constants scoped variable can be used to reference any and all constants that we need to use on the page. Also note that since the class constant path used as the "property name" will always contain at least one period character, we will always need to use the [ ] operator notation.

This gives us a similar mechanism to the EL function described in the previous section, but with a slightly less punctuation-heavy notation.

Is this a wonderfully clever leverage of existing mechanisms, or a delicious violation of the intentions of the Map interface? You decide!

Since there is nothing page-specific about this "constant mapper" class, why bother to declare it on each page using the standard action? If we were to establish the "constant mapper" scoped variable in application scope, it would automatically be available to each and every page in the web application.

The ConstantMapperEstablisher Class

But how would such an application-scoped variable be best established? If we put a action on every page specifying a scope of application that eliminates any advantage of putting the variable into application scope in the first place. We could choose a single page to contain the action, but how could we guarantee that that page will be the first that gets hits after the web application is loaded?

The answer lies not within a JSP at all, but with a servlet context listener. This mechanism allows us to specify a class (actually, any number of classes that we want) that will be notified at web application startup time, giving us the opportunity to execute any initialization code we deem necessary. This is the perfect place to perform any application-level setup such as establishing a scoped variable for our constant mapping class.

The class implements the javax.servlet.ServletContextListener interface and is implemented as:

public class ClassConstantMapperEstablisher implements ServletContextListener {   
   public static final String PARAM_CONSTANT_MAPPER_NAME = 1    
     ClassConstantMapperEstablisher.class.getName() + ".classConstantMapperName";  
    public void contextInitialized( ServletContextEvent servletContextEvent ) 
{ 2         ServletContext servletContext = servletContextEvent.getServletContext();   
      String varName =           servletContext.getInitParameter( PARAM_CONSTANT_MAPPER_NAME );
 3         if (varName == null) { 
4             throw new IllegalStateException( "Context parameter " +      
                                        PARAM_CONSTANT_MAPPER_NAME +            
                                  " must be specified" );         }    
     servletContext.setAttribute( varName, new ClassConstantMapper() );
 5     }      public void contextDestroyed( ServletContextEvent servletContextEvent )
 {} 6  }     

1 Rather than hard-coding the name of the scoped variable to be established into application scope, the name will be specified by a context parameter in the deployment descriptor. In order to avoid possible namespace collisions with other context parameters, the context parameter name is prefixed with the listener class name.

2 The contextInitialized event is triggered by the container when the context is placed into service.

3 The name of the scoped variable to place into application scope is obtained from the context parameter.

4 If the context parameter that specifies the scoped variable name is missing, complain. Loudly.

5 An instance of ClassContantMapper is established in application scope using the name obtained from the context parameter.

6 The contextDestroyed event is triggered when the context is taken out of scope. Nothing need be done in response to this event.

Establishing this class as a context listener for the web application requires two simple entries in the deployment descriptor (web.xml) for the application; one for the required context parameter, and one for the listener:

            org.bibeault.jrjournal.ccc.ClassConstantMapperEstablisher.classConstantMapperName  
        constants                 org.bibeault.jrjournal.ccc.ClassConstantMapperEstablisher           

This effectively creates a new implicit variable named constants that can be accessed in all of our JSP pages (in the same manner as true implicit variables provided by the container such as requestScope).

We have now described three different on-page mechanisms to access constants using our class constant inspector. They're a fairly powerful set of tools, each with their strengths for different circumstances, but they all exhibit a tendency towards on-page verbosity; usually in the guise of long constant path string literals (e.g. "org.bibeault.jrjournal.ccc.test.LoginForm.KEY_USERNAME"). Though this isn't anywhere near a crippling deficiency, there may be situations where something terser may be appropriate.

As previously mentioned, in the Power of the Map article we discussed having the servlet controller construct a Map of all the constants we'd need that we can send to the page as a request-scoped variable. This had the advantage of creating a Map that had simply named keys (as opposed to long class constant field paths). Could a variation on this theme using our "inspector technology" enable us to further simplify on-page constant referencing?

The Action

A lot of the time I find that most, or least a large portion, of the constants referenced within a page are defined within the same class. Consider our LoginForm class example. For all the form elements defined by this abstraction, a class constant representing a string literal for the name of each element is defined. In this example there are only two, but there could be many more for more complicated forms.

We could write code that creates a map of these names and literals (perhaps within the LoginForm class itself) and have the servlet controller establish it as a request-scoped variable before forwarding to the page. But wouldn't it be nice if the page itself could cause such a Map to be established without reliance on the controller or specialized code in the classes that define the constants?

For precisely that purpose we define the custom action. This action will, given a class name, search for all class constants defined by that class and establish a Map of those constants as a scoped variable.

The TLD entry for this tag:

     constantsMap     org.bibeault.jrjournal.ccc.ConstantsMapTag     empty 
            className         true         true          
         var         true         false            
       scope         false         false           

The implementation of the action, for once not relying upon our constant inspector class (though using the same voodoo), is:

public class ConstantsMapTag extends SimpleTagSupport {    
  private String className;     private String varName;   
  private String scopeName;      
public void setClassName( String value ) { this.className = value; } 
    public void setVar( String value ) { this.varName = value; }   
  public void setScope( String value ) { this.scopeName = value; }   
   public void doTag() throws JspException {         try {  
           Map constantsMap = new HashMap(); 1          
   Class declaringClass = Class.forName( this.className );    
         Field[] fields = declaringClass.getFields();
  2     for (int n = 0; n < class="callout" style="">
rgb(0, 128, 0); color: white; padding-top: 0px; padding-right: 8px; padding-bottom: 0px;
 padding-left: 8px; font-size: 14px; font-family: sans-serif; ">
3                 if (Modifier.isPublic( fields[n].getModifiers() ) &&
 4                     Modifier.isStatic( fields[n].getModifiers() ) &&        
             Modifier.isFinal( fields[n].getModifiers() ) ) {       
              constantsMap.put( fields[n].getName(),      
                                 fields[n].get( null) );
 5                 }             }       
      ScopedContext scopedContext = (this.scopeName == null) ?
 6                 ScopedContext.PAGE : ScopedContext.getInstance( this.scopeName ); 
            getJspContext().setAttribute( this.varName,
    7        constantsMap,      scopedContext.getValue() );    
    }         catch (Exception e ) {    
         throw new JspException( "Exception setting constants map for " +       
                              this.className, e );         }     }  }  
   

1 A Map instance to serve as the scoped variable is created.

2 By using the getFields() method, we obtain not only fields defined by the named class, but any fields inherited by extended classes as well. To limit the search to fields declared within the named class we would have used the getDeclaredFields() method.

3 All the located fields are iterated over.

4 Fields not considered "class constants" — that is, public, static and final fields — will be ignored.

5 Any class constants are added to the Map using the field name as the key and the field value as the mapped value.

6 The scope name string is converted to its ScopedContext type-safe enum instance.

7 Finally, the Map is established as a scoped variable using the specified name in the specified scope.

This action's usage for our login form example would be :

  ...  var="LoginForm"/>  ...  
Username: LoginForm.KEY_USERNAME}"/>
Password: LoginForm.KEY_PASSWORD}"/>

Compare this with our original, script-infested example and the "Wouldn't it be nice" scenario that follows it. Is this not just too cool?

But once again, we have a ubiquitous "but"...

We've found a way to make the notation for making class constant references on the pages nice and easy, but have we really gained anything over just hard-coding the values directly onto the pages? Recall that when we did so, any errors in the names resulted in a non-specific run-time bug ("Why is the blasted username parameter always blank?"). But when we used scriptlet expressions that referenced class constants and made a similar typo, an error was reported at translation time. What happens when we use our mechanism?

When an EL reference is made to a Map using a key that does not exist, no error is thrown. Rather, a default is provided for the evaluation of the EL expression in which the reference was made. In a textual context, such as we are using here, the default is the empty string. Therefore, when we make a mistake such as ${LoginForm.KEY_USRENAME} in typing the class constant name, the result will be a blank in the place of the EL expression.

Well, poo! While that's marginally better than simply hard-coding the name -- errors will result in predictable and invalid HTML patterns such as name="" which is easier to search for than mis-typed names -- it's still a far cry from the satisfying in-your-face error thrown when we use scriptlet expressions and constant references.

Is there something we can do about that?

The ClassConstantsMap Class

Because our class constant inspector is a run-time mechanism, we can't detect and report errors at translation time. But to achieve the goal of having the page blow up in our faces when we make a error in class constant references, a run-time error, as long as it is loud, obnoxious and obvious, will serve just as well.

Our problem arises from the fact that when the get() method of any java.util.Map is called with a key that does not exist, it returns a null which the EL goes about converting to a default value suitable for the referencing evaluation context.

That's not what we want in this case: what we want is for the Map to raise hell if we try to fetch a nonexistent key. Since all the other behaviors of the java.util.HashMap class that places into a scoped context work exactly as we would like, all we need to do in order to achieve the behavior we'd like to see is to extend the HashMap class with a new implementation of its get() method.

The implementation is simple:

public class ClassConstantsMap extends HashMap {    
  private String className;    
  public ClassConstantsMap( String className ) 
{ 1         super();         this.className = className;     }  
    public Object get( Object key ) {
 2         if (super.get(  key ) == null)
 3             throw new IllegalArgumentException( "Key " + key +          
       " could not be found in class constant map for " +          
                                        this.className );         return super.get( key );
 4     }  }     

1 The constructor accepts the name of the class from which the Map is being constructed. This is used primarily during error reporting, which is the entire reason for the existence of this class in the first place. This class name is stored in an instance variable for later use.

2 Like any other implementation of java.util.Map, the get() method is invoked when an EL reference is made.

3 A check for the existence of an entry for the passed key is made and an exception is thrown if one does not exist. Note that no special considerations are made for entries that do exist but have a value of null. In our scenario, we are making no distinctions between null entries and entries that do not exist.

Since neither null values nor null keys make much sense in this scenario, it would also be an easy matter to extend the HashMap's put() method to not accept null for either the key or the value of an entry.

4 If the entry exists, it is returned via the extended HashMap's get() method.

By changing the Map class used in the handler for from HashMap to our newClassConstantsMap class, we finally achieve our goal. We can easily make class constant references on the JSP page without resorting to scriptlet expressions, and if we make referencing errors, we will learn about them very quickly and spectacularly.

This time, there are no substantive "but's", and that's cool!

Happy Days are Here Again

In this article we've established a general means for determining the value of a class constant and explored a number of ways to exploit this capability to ease the pain of referencing class constants in JSP pages.

Hopefully, we have either created ready-made tools that you can begin to use in your scriptless JSP pages immediately, or have given you ideas and technology fragments that you can exploit in whatever manner makes the most sense for your own web applications.

Resources

Files

ccc.jar
The jar file containing the classes and TLD described in this article. This jar file is suitable for dropping into a web application's WEB-INF/lib folder in order to use these tags and classes as is.

This jar file also contains the source code for all the classes described in this article, as well as the generated javadocs for the classes and the TLD.

You will note that the classes in the jar file differ in a number of ways from those presented in this article. Some of the code presented in the body of the article has been simplified to focus upon the concepts being discussed. The actual classes as included in the jar file have more robust error checking, and common operations are factored into superclasses. Of particular note:

  • The custom action implementations define TagExtraInfo inner classes to perform translation-time checking of their static attributes.
  • Since both of the defined custom actions share the declaration and semantics of the var andscope attributes, a "tag support" superclass for these tags handles those semantics. This superclass is suitable for extending by any custom action supporting these common attributes.

The JSP 2.0 Specification
The definitive reference for JSP 2.0 information.

Javadoc API

java.lang.reflect
The javadoc API descriptions for the reflection classes.
java.util.Map
The javadoc API for the java.util.Map interface.
javax.servlet.ServletContextListener
The javadoc API descriptions for the javax.servlet.ServletContextListener class.