Archive for the ‘JSP’ Category

JSP Comments within Comments

Monday, August 4th, 2008
Have you ever run into that frustrating situation where you have JSP comments in your code, and need to comment out a large block of code that
contains those comments.  The situation looks something like this:

<%@ taglib uri=“http://java.sun.com/jsp/jstl/core” prefix=”c” %>
<%@ taglib uri=“http://java.sun.com/jsp/jstl/functions” prefix=”fn” %>

<c:if test=”${!empty param.userInput}”>
<%– Trim the userInput –%>
<c:set var=”trimmedUserInput” value=”${fn:trim(param.userInput)}”>
</c:if>

<html>
<form action=”.”>

<p>
-${param.userInput}–${trimmedUserInput}-
</p>

<p>
User input: <input type=”text” name=”userInput” value=” Some Input.
“>
</p>
<p>
<input type=”submit”>
</p>
</form>
</html>

Now say you wanted to comment out the <c:if> block for testing ... the
problem is this won't work:

<%–
<c:if test=”${!empty param.userInput}”>
<%– Trim the userInput –%>
<c:set var=”trimmedUserInput” value=”${fn:trim(param.userInput)}”>
</c:if>
–%>

because the inner comments "break" the outer comments (it's just not legal
syntax).  What to do?  A nice way to deal with this is to use the following
syntax for your general comments:

<% // Trim the userInput %>

You can legally wrap that syntax with <%-- --%> style comments!  So the
above code, with the test comments included would look like:

<%@ taglib uri=“http://java.sun.com/jsp/jstl/core” prefix=”c” %>
<%@ taglib uri=“http://java.sun.com/jsp/jstl/functions” prefix=”fn” %>

<%–
<c:if test=”${!empty param.userInput}”>
<% // Trim the userInput %>
<c:set var=”trimmedUserInput” value=”${fn:trim(param.userInput)}”>
</c:if>
–%>

<html>
<form action=”.”>

<p>
-${param.userInput}–${trimmedUserInput}-
</p>

<p>
User input: <input type=”text” name=”userInput” value=” Some Input.
“>
</p>
<p>
<input type=”submit”>
</p>
</form>
</html>

Happy documenting!

Manipulating Lists in JSTL

Wednesday, May 21st, 2008

A common problem when coding in JSTL is that you would like to have an ArrayList of items that you can iterate over. For example imagine that you have a list of Animals like:

1) Sylvester

2) Goofy

3) Mickey

<c:forEach items="${animalList}" var="animal">${animal}<</c:forEach>

And you would like the output to be in the same order:

Sylvester

Goofy

Mickey

The problem is that you can’t do this:

<jsp:useBean id=”animalList” class=”java.util.ArrayList”/>

because <c:set> doesn’t work with <i>ArrayLists</i>, and so there is no good way to use JSTL to add those values.

This fails:

<c:set target=”${animalList}” value=”Sylvester”/>

<c:set target=”${animalList}” value=”Goofy”/>

<c:set target=”${animalList}” value=”Mickey”/>

You could do this, and I wouldn’t argue if you do:

<c:set var=”dummyVar” value=”${animalList.add(’Sylvester’)}”/>

<c:set var=”dummyVar” value=”${animalList.add(’Goofy’)}”/>

<c:set var=”dummyVar” value=”${animalList.add(’Mickey’)}”/>

However, its a little ugly, because you have to use dummyVars. Still I will admit I have used this technique a lot. Another solution that you might be considering is to use HashMaps, which do work with <c:set>.

<jsp:useBean id=”animalMap” class=”java.util.HashMap”/>

<c:set target=”${animalMap}” property=”cat” value=”Sylvester”/>

<c:set target=”${animalMap}” property=”dog” value=”Goofy”/>

<c:set target=”${animalMap}” property=”rat” value=”Rat”/>

<c:forEach items=”${animalMap.values()}” var=”animal”>

${animal}<br>

</c:forEach>

This is cool because there is not hackish method calls on objects that JSTL doesn’t understand. Also the elements can now be referenced indirectly, instead of having to loop on the list to find a particular element. But there is a problem: The order has been lost! When this loop fires it dumps the animals in the order that they are stored in the HashMap, which for all practical purposes is random.

The solution: <b>java.util.LinkedHashMap</b>

By replacing java.util.HashMap in the example above with

java.util.LinkedHashMap, you get the best of both worlds! <b>Ordered

elements</b> and <b>Indirect Reference</b>:

<jsp:useBean id=”animalMap” class=”java.util.LinkedHashMap”/>

<c:set target=”${animalMap}” property=”cat” value=”Sylvester”/>

<c:set target=”${animalMap}” property=”dog” value=”Goofy”/>

<c:set target=”${animalMap}” property=”rat” value=”Rat”/>

These are ordered:<br>

<c:forEach items=”${animalMap.values()}” var=”animal”>

${animal}<br>

</c:forEach>

And this references a particular element:<br>

${animalMap['dog']}

Removing an item from a Map using JSP

Friday, November 30th, 2007

A common need for working with Maps in JSP is the ability to remove items from the Map.  With JSTL it is not so obvious how to do this, yet it turns out to be very easy by simply using an EL expression to call the remove(key) method on the map.  Here is an example…

 

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<html>
<body>

<p>Creating hash map and populate it ..</p>

<jsp:useBean id="map" class="java.util.HashMap"/>
<c:set target="${map}" property="cat" value="brown"/>
<c:set target="${map}" property="dog" value="green"/>
<c:set target="${map}" property="rat" value="black"/>

<p>Remove dog and store its former value in a local variable …</p>

<c:set var="oldDogValue" value="${map.remove(’dog’)}"/>

</body>
</html>

Another great tip from Aaron Freeman at SendThisFile.com.

Handling multiple value parameters in JSP

Friday, November 9th, 2007

In JSP, you cannot simply use an expression like ${param.weekday} to retreive multiple values if the request has multiple values assigned like the form below…

<input name="weekday" value="Sunday" checked>
<input name="weekday" value="Monday" checked>

Instead, use an expression like ${fn:join(paramValues['weekday'], ‘,’)} to retreive a comma delimited list of values for the parameter.

Tip provided by Aaron Freeman from SendThisFile.com.

The 16 String Functions Available in JSP EL

Friday, December 1st, 2006

Although I’ve used JSP extensively for quite sometime, I didn’t realize until recently that JSTL supports 16 string functions within the EL syntax.  Here is an example JSP page that exercises the 16 string functions…


<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<html><body>

contains() --> ${fn:contains('Hello', 'el')}<br>
containsIgnoreCase() --> ${fn:containsIgnoreCase('HELLO', 'el')}<br>
endsWith() --> ${fn:endsWith('Hello', 'llo')}<br>
escapeXml() --> ${fn:escapeXml('1<>3')}<br>
indexOf() --> ${fn:indexOf('Hello', 'el')}<br>
join()/split() --> ${fn:join(fn:split('/1/2/3/4/5', '/'), ':')}<br>
length() --> ${fn:length('Hello')}<br>
replace() --> ${fn:replace('Hello', 'H', 'J')}<br>
startsWith() --> ${fn:startsWith('Hello', 'He')}<br>
substring() --> ${fn:substring('Hello', 2, 4)}<br>
substringAfter() --> ${fn:substringAfter('Hello', 'el')}<br>
substringBefore() --> ${fn:substringBefore('Hello', 'el')}<br>
toLowerCase() --> ${fn:toLowerCase('HELLO')}<br>
toUpperCase() --> ${fn:toUpperCase('hello')}<br>
trim() --> ${fn:trim('  hello  ')}<br>

</body></html>

This outputs the following…


contains() --> true
containsIgnoreCase() --> true
endsWith() --> true
escapeXml() --> 1<>3
indexOf() --> 1
join()/split() --> 1:2:3:4:5
length() --> 5
replace() --> Jello
startsWith() --> true
substring() --> ll
substringAfter() --> lo
substringBefore() --> H
toLowerCase() --> hello
toUpperCase() --> HELLO
trim() --> hello

You can see the full reference for these string functions here.  This requires JSP 2.0.

You can also find an excellent article on creating a custom JSP function here:)

Manipulate a HashMap With Only JSTL Tags in JSP

Tuesday, November 28th, 2006

There is no need to write Java or custom tags when all you need to do is store and retrieve data with a simple HashMap.  The trick is to instantiate the HashMap using a <jsp:useBean> tag and then populate it using a <c:set target=..> tag.  You can instantiate and store data in a HashMap with JSTL tags like this (paste the code into your own test.jsp page and give it a try):

——– CUT HERE ——–
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<jsp:useBean id="exampleMap" class="java.util.HashMap"/>
<c:set target="${exampleMap}" property="KS" value="Kansas"/>
<c:set target="${exampleMap}" property="TX" value="Texas"/>
<c:set target="${exampleMap}" property="OK" value="Oklahoma"/>

<c:set var="state" value="TX"/>

<html>
<body>
    Method 1: ${exampleMap.TX}<br>
    Method 2: ${exampleMap['TX']}<br>
    Method 3: ${exampleMap[state]}<br>
</body>
</html>
——– CUT HERE ——–

The target attribute of the <c:set> tag indicates which HashMap you are manipulating.  The property attribute is the HashMap key. The value attribute is the element to be placed in the HashMap that is associated with the key. 

Running the above JSP page will result in the following output:

Method 1: Texas
Method 2: Texas
Method 3: Texas

Of course you can also populate the HashMap with values from a database by just including the <c:set target=… > tag within a <c:forEach .. > block.

Three Ways to Select a List Option in JSP

Tuesday, November 14th, 2006

A common task in JSP is choosing the right option in list based on a parameter  There are three key ways to do this and I’ve outlined each below.

In the beginning, we had an ugly syntax for selecting an option in a list in JSP via scriptlets

<select name="answer">  <option name="yes"    <%= "yes".equals(request.getParameter("answer")) ? "selected" : "" %>>Yes  <option name="no"    <%= "no".equals(request.getParameter("answer")) ? "selected" : "" %>>No</select>

Then we got JSTL which allows us to select an option in a list via the if tag (part of the JSTL custom tags)…

<select name="answer">  <option name="yes"    <c:if test="${param.answer=='yes'}">selected</c:if>>Yes  <option name="no"    <c:if test="${param.answer=='no'}">selected</c:if>>No</select>

Now with JSP 2.0, we can select the option directly via an EL expression like this…

<select name="answer">  <option name="yes"    ${param.answer=='yes' ? 'selected' : ''}>Yes  <option name="no"    ${param.answer=='yes' ? 'selected' : ''}>No</select>

I prefer this last syntax — it appears more readable to me than the prior two alternatives.

How To Create Custom Functions in JSP Expressions

Monday, November 13th, 2006

With JSP 2.0, you can use custom functions within the JSP EL syntax — this turns out to be incredibly useful and underutilized IMO.  Here is a start-to-finish example of a JSP EL custom function that creates a string replacement custom function…

  1. Create a java class containing a static replace() method like this…

    package com.mycompany;
    
    public class MyFunctions {  public static String replace(String source, String x, String y) {    if (source==null) return null;    else source.replaceAll(x, y);  }}
  2. Create a TLD file using the JSP 2.0 declarations like this…
    <taglib xmlns="http://java.sun.com/xml/ns/j2ee" version="2.0">  <tlib-version>1.0</tlib-version>  <short-name>abc</short-name>  <uri>http://www.mycompany.com/taglib/abc</uri>  <function>    <name>replace</name>    <function-class>com.mycompany.MyFunctions</function-class>    <function-signature>    String replace(java.lang.String,java.lang.String,java.lang.String)    </function-signature>  </function></taglib>
  3. Use the new replace() function in your JSP page like this…
    <%@ taglib prefix="c"   uri="http://java.sun.com/jsp/jstl/core" %><%@ taglib prefix="abc" uri="http://www.mycompany.com/taglib/abc" %><html><body>${abc:replace('This is a good test','good','bad')}</body></html>
  4. Open your JSP page and you should see This is a bad test.

That’s it.  The JSP EL custom functions are very useful and can often replace creating custom tags for simple functions.