Friday, March 11, 2011

Clean your JSP Code with JSTL & JSP EL

Note: After writing this blog I realized 3rd party templating engines like Velocity or FreeMarker are viable alternatives to JSTL & JSP EL. However JSTL & JSP EL are the standard and have official support while the others do not. I may write a couple follow up blogs in the future detailing how to use Velocity or FreeMarker.

Below is an example of mixing HTML with JSP scriptlets and expressions:

<% if (user.getRole().equals("member")) { %>
    <p>Welcome, <%=user.getName() %>!</p>
<% } else { %>
    <p>Welcome, guest!</p>
<% } %>

The mixing and HTML's syntax and Java's syntax makes the code ugly and hard to read and understand. It can also encourage bad coding practices; it is sometimes tempting to add additional business logic in your JSP files. JSTL and JSP EL were created to remedy this situation.

JSTL (JSP Standard Tag Library) is a standardized tag library that can be used to replace JSP scriptlet tags (<% %>) inside of JSP files. It has tags for all the most common operations necessary to create your JSP file (conditional tags, looping tags, formatting tags, etc).

JSP EL (JSP Expression Language) is an expression language that can be used to replace JSP expression tags (<%= %>) inside your JSP files. JSP EL has many convenient shortcuts and allows for a much simpler syntax to manipulate application data.

JSTL has integrated support for JSP EL; JSP EL can be used inside of the JSTL tag attributes. If your application server supports JSP 2.0 specification or greater then JSP EL can also be used outside of the JSTL tag attributes; otherwise you will need to wrap your expression using the JSTL out tag (see example below). Using JSTL combined with JSP EL the above code becomes:

<c:choose>
<c:when test="${user.role == 'member'}">
    <p>Welcome, <c:out value="${user.name}"/>!</p>
</c:when>
<c:otherwise>
    <p>Welcome, guest!</p>
</c:otherwise>
</c:choose>

As you can see the code is much improved compared to its original state. Finally, you can rid yourself of all the ugly JSP tags.

JSTL may or may not be included with your application server. If it is not included you can download the JAR files and add them to your project's WEB-INF/lib folder or to your application server's shared library folder. The JSTL version you need to download will vary based on which JSP specification version your application server supports. Below is a table that maps the JSTL version to the JSP specification version:

Servlet VersionJSP VersionJSTL VersionJava EE Version
2.52.11.25
2.42.01.11.4
2.31.21.01.2

Note: I am having great difficulty trying to find downloads for the older versions of JSTL. The download links on the Jakarta site are broken. I have not found a solution to this problem yet.

For more information see the following links:

No comments:

Post a Comment