Develop JSPs : How to avoid scriplets and write readable, maintainable JSP Code – Best Practice

Introduction

JSP Standard Tag Library, JSTL , was developed to provide standard way of developing JSPs without the need to write too many scripts as the JSP goes larger. It can be used to provide XML JSP pages that has no ugly scriplets. It provides same core JSP functions, using simple tags, providing structural tasks (conditions and looping), localization & internationalization tasks (using resource bundle & messages.

In this article, we will demonstrate some practices that most JSP developers are familiar with, writing scriplets. Though, I am providing the JSTL way to the same task.

What can be done using scriplets, can be also done using JSTL, easily

Case Scriplet JSTL
Output Text <b>Hello <%= user %>.</b> <b>Hello <c:out value=’${user}’ default=’guest’ />.</b>
Looping without scripting <table>
<% String[] items = (String[]) request.getAttribute(“movieList”);
String var=null;
for (int i = 0; i < items.length; i++) {
var = items[i];
%>
<tr><td><%= var %></td></tr>
<% } %>
</table>
<table>
<c:forEach var=”movie” items=”${movieList}” varStatus= ”movieLoopCount” >
<tr>
<td> Count: ${movieLoopCount.count}  </td>
</tr>
<tr>
<td>${movie} <br><br></td>
</tr>
</c:forEach>
</table>
Conditions <% if( userType.equals("member") ) { %>
<jsp:include page=”inputComments.jsp”/>
<%}%>
<c:if test=”${userType eq ‘member’ }” >
<jsp:include page=”inputComments.jsp”/>
</c:if>
If-Else or Switch case <% String pref = (String) session.getAttribute(“userPref”);
if (pref.equals(“performance”)) {
out.println(“Now you can stop even if you <em>do</em> drive insanely fast.”);
} else if (pref.equals(“safety”)) {
out.println(“Our brakes won’t lock up, no matter how bad a driver you are. “);
} else if (pref.equals(“maintenance”)) {
out.println(“ Lost your tech job? No problem--you won’t have to service these
brakes for at least three years.”);
} else {
// userPref doesn’t match those, so print the default headline
out.println(“Our brakes are the best.”);
} %>
<c:choose>
<c:when test=”${userPref == ‘performance’}”>
Now you can stop even if you <em>do</em> drive insanely fast.
</c:when>
<c:when test=”${userPref == ‘safety’}”>
Our brakes will never lock up, no matter how bad a driver you are.
</c:when>
<c:when test=”${userPref == ‘maintenance’}”>
Lost your tech job? No problem--you won’t have to service these brakes
for at least three years.
</c:when>
<c:otherwise>
Our brakes are the best.
</c:otherwise>
</c:choose>
Setting variables <% session.setAttribute("userLevel", "Cowboy"); %> <c:set var=”userLevel” scope=”session” value=”Cowboy” />
Using <c:set> with beans and Maps <%pageContext.setAttribute("map1", map1);
Map map = (Map) pageContext.getAttribute("PetMap);
map.put("dogName", "Clover"); %>
<c:set target=”${PetMap}” property=”dogName” value=”Clover” />
Remove bean <% request.removeAttribute( "userStatus"); %> <c:remove var=”userStatus” scope=”request” />
URL Encoding <%
String first = "Crouching Pixels";
String last = "Hidden Cursor";
%>
<a href="/inputComments.jsp?first=<%=first%>&last=<%=lasr%>" />
<c:set var=”last” value=”Hidden Cursor” />
<c:set var=”fi rst” value=”Crouching Pixels”/><c:url value=”/inputComments.jsp” var=”inputURL” >
<c:param name=”firstName” value=”${first}” />
<c:param name=”lastName” value=”${last}” />
</c:url>
Handling Exceptions <%
String errorMsg = "";
int x = 0;
try
{
x = 10/0;
}
catch(Exception e)
{
errorMsg = e.getMessage();
}
%>
There was an exception : <%=errorMsg%>
<c:catch var=”myException”>
Inside the catch...
<% int x = 10/0; %>
</c:catch>
<c:if test=”${myException != null}”>
There was an exception: ${myException.message} <br>
</c:if>
attribute named “myException
assigns the exception object to

JSTL benifits

  • Write Java code that is written in a more readable format with helpful indentation, in less lines.
  • Write maintainable code that could be easily understood instead of ambiguous brackets and scriplets in JSP code.
  • Prevents cross-site hacking, by preventing rendering javascripts tag to be rendered and interpreted in browser.
  • Web designers can easily apply css designs on any JSP developed using only JSTLs, with no scriplets.

When JSTL tags does not have the needed functionality

You can always build your own custom tag, building your TLD files and the Tags handler classes to provide something complex in JSP. You can refer to “Development with JSP and XML– Part III: Developing JSP Custom Tags” article to see an example of building custom JSP tags.

References

Head First Servlets and JSP, Second Edition

Advertisements
Categories JavaTags , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close