JavaServer Pages (JSP) and JSTL – trouble with JSPs and forms

Hi, I am working on the my final project for my 3rd java class. We have learned servlets, and JSPs. I need to save all of the information into a database. The problem I am having is how to make all the form information only submit on the final page. I have made a jsp which shows a different ‘page’ depending on the page1, page 2 boolean values. If page1 = true; then page1 is showing, if page2 = true; page 2 is showing. The problem I’m having is how to change the boolean values when the person hits the first next button. (I currently have it as a sumit button because I don’t know how to get to the second page). Any help or thougts on this matter would be appreciated. thanks.

Here is part of the code”

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page contentType="text/html;charset=windows-1252"%>
<%! private Boolean _page1 = true; %>
<%! private Boolean _page2 = false; %>
<html>
<jsp:useBean id="resume" class="Sheridan.Resume"/>
<jsp:setProperty name="resume" property="*"/>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"/>
    <title>ResumeBuilder</title>
  </head>
  <body>
    <form name="input" action="sheropolisservlet" method="post">
      <% if (_page1 == true)
  {%>
      <p>Personal Information</p>
      <p>Name:</p>
      <table cellspacing="2" cellpadding="3" border="1" width="100%">
        <tr>
          <td width="13%">First Name:</td>
          <td width="87%">
            <input type="text" name="_firstName" maxlength="20" size="20"/>
          </td>
        </tr><tr>
          <td width="13%">Last Name:</td>
          <td width="87%">
            <input type="text" name="_lastName" maxlength="20" size="20"/>
          </td>
        </tr><tr>
          <td width="13%">Middle Initial:</td>
          <td width="87%">
            <p>
              <input type="text" name="_middleInitial" maxlength="1" size="1"/>
            </p>
          </td>
        </tr>
      </table>
      <p>Address:</p>
      <table cellspacing="2" cellpadding="3" border="1" width="100%">
        <tr>
          <td width="50%">
            <p>Street Number and Name:</p>
          </td>
          <td width="50%">
            <input type="text" name="_street" maxlength="20" size="20"/>
          </td>
        </tr><tr>
          <td width="50%">City:</td>
          <td width="50%"> </td>
        </tr><tr>
          <td width="50%">Province:</td>
          <td width="50%"> </td>
        </tr><tr>
          <td width="50%">Postal Code:</td>
          <td width="50%"> </td>
        </tr><tr>
          <td width="50%">Country:</td>
          <td width="50%"> </td>
        </tr>
      </table>

      <p>
        <a href="http://127.0.0.1:7101/Sheropolis-Michelle-Project1-context-root/ResumeBuilderForm2.html">RESET</a>
      </p>

      <p>
        <input type = "submit" value = "NEXT">
      </p>
      <%}%>

      <% if (_page2 == true)
  {%>
      <p>Employment Objective:</p>
      <p>Career Objective:</p>
      <p>Programming Languages:</p>
      <p>Operating Systems:</p>
      <p>Responsibilities:</p>
      <p>Software Development Areas:</p>
      <p> </p>
      <a href="http://127.0.0.1:7101/Sheropolis-Michelle-Project1-context-root/ResumeBuilderForm2.html">RESET</a>
      <a href="http://127.0.0.1:7101/Sheropolis-Michelle-Project1-context-root/ResumeBuilderForm2.html">PREVIOUS</a>
      <input type="submit" value="Save"/>
      <%}%>
      <p>
        <a href="http://127.0.0.1:7101/Sheropolis-Michelle-Project1-context-root/ResumeBuilderForm2.html">HOME</a>
      </p>
    </form>
  </body>
</html>

My suggestion is fairly straightforward.
 If you have two pages, then it should be two seperate jsp pages, not one jsp page which conditionally displays one page or the other.
 Your servlet should be responsible for directing to the correct by using a RequestDispatcher to forward to the appropriate jsp to display a result.
 Have you covered the MVC (Model-view-controller) pattern in your class?

 The URLs in your page are hardcoded to your machine: <a href="http://127.0.0.1:7101/Sheropolis-Michelle-Project1-context-root/ResumeBuilderForm2.html">HOME</a>

 I would suggest that you use a website relative link.  
 ie: <a href="/Sheropolis-Michelle-Project1-context-root/ResumeBuilderForm2.html">HOME</a>
 or even better
 <a href="${pageContext.request.contextPath}/ResumeBuilderForm2.html">HOME</a>

 If you have a multiple jsp page "wizard" then you probably want to store state in the session - probably in a java bean.
 It would be easier to use javabeans if you didn't name all your fields starting with _.

JSTL Examples

JSTL Examples
Select font size:
8pt 9pt 10pt 11pt 12pt 14pt 16pt
Download the

JSTLexamples.war
archive. This archive contains the following files:

index.jsp Script with a variety of examples
bean/MyBean.java User-defined bean example
mytaglib/MyFunctions.java JSTL tag library classes
Functions.tld JSTL tag library definition
Install and run in Eclipse
Prior to starting eclipse, you need to make available two new library JAR files which are included in the apache-tomcat distribution but not available for all applications. Locate the directory:

apache-tomcat-6.0.14/webapps/jsp-examples/WEB-INF/lib/

and within it, the files:

jstl.jar standard.jar

Simply copy these two files into:

apache-tomcat-6.0.14/common/lib/

Then start up eclipse. Follow the steps in JSP Forms import the WAR file JSTLexamples.war and run the project on Tomcat.

The JSP Standard Tag Library (JSTL)
The JSTL library provides a means, through variables, expressions and tags, to avoid the interleaving of Java and tag-style code. Using this language, we can, for the most part, eliminate explicit Java code in JSP pages in favor of augmenting the XML-like tag structure. See

http://jakarta.apache.org/taglibs/
http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/
You should refer to this online documentation:

jstl tld docs
and/or download it yourself:

jstl-1_1-mr2-spec-tlddoc.zip
The standard tags are those described in the table below. We have omitted the sql tags since we don’t plan to use SQL done directly in JSP. Using one of tag groups is effected by the addition of one of the following respective tag statements below.

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

The uri is simply an identifier of the tag set. The prefix is determinable by the user, but the prefixes seen here are standard.

TLD tags and functions c: core fmt: formatting fn: functions x: xml
c:catch
c:choose
c:forEach
c:forTokens
c:if
c:import
c:otherwise
c:out
c:param
c:redirect
c:remove
c:set
c:url
c:when
fmt:bundle
fmt:formatDate
fmt:formatNumber
fmt:message
fmt:param
fmt:parseDate
fmt:parseNumber
fmt:requestEncoding
fmt:setBundle
fmt:setLocale
fmt:setTimeZone
fmt:timeZone
fn:contains()
fn:containsIgnoreCase()
fn:endsWith()
fn:escapeXml()
fn:indexOf()
fn:join()
fn:length()
fn:replace()
fn:split()
fn:startsWith()
fn:substring()
fn:substringAfter()
fn:substringBefore()
fn:toLowerCase()
fn:toUpperCase()
fn:trim()

x:choose
x:forEach
x:if
x:otherwise
x:out
x:param
x:parse
x:set
x:transform
x:when

These and other tag systems are used in JSP in one of two forms:

<tag-prefix:type attribute1=”VALUE1″ …

or, as functions to create expressions:

tag-prefix:function(arg1,arg2,…)

As in XML, tags can be complete, using a single tag ending with “/>“, or in pairs, containing a content terminated by a matching ending tag </tag-prefix:tag-type>. Some example of the common usages of the “c” tags are these:

<c:out value=”…” escapeXml=”true”/>
<c:set var=”x” value=”…” />
<c:if test=”…” > … </c:if>
<c:forEach var=”x” items=”…” > … </c:forEach>

Expression Language (EL)
The syntax for what replaces the “…” above is specified by a Java-like language, unimaginately called Expression Language (EL). EL is part of JSP; its expressions are all surrounded by the syntax ${ }. but typically can only be used most effectively in conjunction with JSTL tags. EL is closely related to Java but has some extensions and conceptual simplifications. In particular, EL is more like other web script languages being loosely typed along with other semantic simplifications. EL expressions permit variables and most of the usual arithmetic and boolean operators. Here are some points:

The == operator for strings functions like the Java .equals operator.
an EL expression with an undefined value, which (normally represented by null in Java) is also represented by null in EL, but is equivalent to the empty string.
EL has a unary operator empty: empty(x) acts like the expression x==null but also means “x equals the empty string”.
the operators or, and are synonyms for ||, &&, respectively.
Query parameters
The value of the parameter “xx” is expressed by the EL expression param.xx. When used directly in HTML,

${param.xx}

is equivalent to the JSP expression:

<%= (request.getParameter(“xx”) != null) ? (request.getParameter(“xx”) : “” %>

Session variables are EL variables
A session variable x automatically becomes available as an EL variable, e.g. if we have:

<%
session.setAttribute( “x”, “hello” );
// or
pageContext.setAttribute( “x”, “hello” );
%>

x = ${x} <!– prints: x = hello — >

JSP beans in JSTL
The EL language provides a simplified syntax for accessing bean’s get/set accessor functions. For example, the bean we use in the examples below is this:

<jsp:useBean id=”mb” class=”bean.MyBean” />

from the class:

——————————————————————————– bean/MyBean.java

package bean;

public class MyBean {
private String count;
public String getCount() { return count; }
public void setCount(String count) { this.count = count; }
public MyBean() {
System.out.println(”MyBean intialized”);
count = “0?;
}
}
EL treats the expression ${mb.count} as the value of mb.getCount(). A typical JSTL tag statement is something like

<c:set var=”i” value=”${mb.count}” />

The c:set tag is also used to call the set member function as follows:

<c:set target=”${mb}” property=”count” value=”5″ />

is equivalent to mb.setCount(”5?). Caution: If you use both set and get property, they must be consistent. For example, suppose you have these member functions:

String getSomeProperty() { … }
void setSomeProperty(int n) { … }

Then EL will consider this a mismatch and most likely reject the setter member function if you tried to use:

<c:set target=”${mb}” property=”someProperty” value=”5″ />

We can also remove a bean from the session using the JSTL c:remove tag:

<c:remove var=”mb” />

Data structures: arrays, arrays, maps, sets
Arrays and maps permit access to their collection via indices: arrays via integer indices and maps via key indices. EL regards both of these accesses as syntactically similar using the [ ] operator. For example:

<%
Map<String,String> theMap = new HashMap<String,String>();
theMap.put(“John”, “5”); theMap.put(“Jim”, “7”);
String theArray[] = { “aaa”, “bbb”, “ccc” };

session.setAttribute( “theMap”, theMap );
session.setAttribute( “theArray”, theArray );
%>

${theMap[“Jim”]} <!– same as theMap.get(”Jim”), outputs 7 –>
${theArray[1]} <!– outputs bbb –>

The EL expressions for maps, sets and lists can all print directly. Arrays,
as in Java, don’t print directly, but must use an auxiliary function. In this case the fn:join function serves the purpose:

${fn:join(theArray,”,”)}

Iterating over data structures
In order to iterate over an array, list, map, or set, the c:forEach tag pair serves our interests. Iteration with c:forEach treats arrays, lists and sets identically. For example, this code will iteratively print the elements:

<!– L represents either an array, list or set –>
<c:forEach var=”x” items=”${L}” >
${x}
</c:forEach>

When using a map, the iteration generates Map.Entry pairs. Using the getKey and getValue functions the structure of the JSTL code to iteratively print the key/value pairs looks like this:

<!– M is a map –>
<c:forEach var=”x” items=”${M}” >
${x.key}: ${x.value}
</c:forEach>

Choice tags c:if, c:choose/c:when
The c:if tag generates a choice situation with a syntax like:

<c:if test=”${EL_BOOLEAN_EXPRESSION}” > … </c:if>

The EL_BOOLEAN_EXPRESSION uses the usual boolean operators with simplifications and additions as mentioned above. If-else structures are based on the c:choose/c:when/c:otherwise tags:

<c:choose>
<c:when test=”${EL_EXPR1}”> … </c:when>
<c:when test=”${EL_EXPR2}”> … </c:when>

<c:otherwise> … </c:otherwise>
</c:choose>

User-generated tag functions
If one wants to avoid explicit JSP sections of code then the Java classes and functions must be able to be accessed through the tag system. Beans provide a limited way of doing so through combinations of “get/set” member functions, but this is not intended for utility functions to manipulate objects. The fn tags provide some of these utility functions, but one can imagine that soon there would be need for your own specific utility functions. Towards this end, JSP provides a means to add your own tag libraries using a combination of Java classes and Tag Library Definition (TLD) files. Both XML-like tags and EL function tags can be added, but it’s much easier to create user-defined EL function tags. The utility functions used must be static functions. For example, suppose we want to use the function defined in this class in an EL expression.

——————————————————————————– mytaglib/MyFunctions.java

package mytaglib;
import java.util.*;
public class MyFunctions {
public static boolean contains(Set<String> set, String target) {
return set.contains(target);
}
}
The glue which connects this functions to JSP is the XML file MyTags.tld held stored in the /WEB-INF/ project directory.

——————————————————————————– MyTags.tld

<?xml version=”1.0? encoding=”UTF-8??>
<taglib version=”2.0? …>
<tlib-version>1.1</tlib-version>
<uri>/WEB-INF/MyTags</uri>
<function>
<name>contains</name>
<function-class>mytaglib.MyFunctions</function-class>
<function-signature>
boolean contains(java.util.Set,java.lang.String)
</function-signature>
</function>
</taglib>
This file defines a uri by which it is accessed and a set of function prototypes in XML format. Each function has a tag name, the class it belongs to and the actual function prototype within this class. The necessary specification within the JSP file is something like this:

<%@taglib prefix=”mtg” uri=”/WEB-INF/MyTags”%>

The prefix chosen specifies how the function will be referenced within the EL syntax — it can be anything you want, so long as it doesn’t conflict with another tag set. In this case the function will be prefaced by mtg: as in this example:

<c:if test=”${mtg:contains(someSet,someValue)}” > … </c:if>

Example script
——————————————————————————– index.jsp

<%@ page language=”java” contentType=”text/html;
charset=US-ASCII” pageEncoding=”US-ASCII”%>

<%@page import=”java.util.*”%>

<%@taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core”%>
<%@taglib prefix=”fn” uri=”http://java.sun.com/jsp/jstl/functions”%>
<%@taglib prefix=”mtg” uri=”/WEB-INF/MyTags”%>

<jsp:useBean id=”mb” scope=”session” class=”bean.MyBean” />

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=US-ASCII”>
<title>Insert title here</title>
<style>
h4 { color: red; margin-bottom:0px; text-decoration: underline; }
</style>
</head>
<body>
<%
String x = “testing”;
String[] a = { “xx”, “yy”, “zz” };

Map<String, String> m = new LinkedHashMap<String, String>();
m.put(”aa”, “1?);
m.put(”bb”, “2?);
m.put(”cc”, “3?);

List<String> l = new ArrayList<String>();
l.add(”nn”);
l.add(”mm”);
l.add(”oo”);
Set<String> s = new LinkedHashSet<String>();
s.add(”aa”);
s.add(”bb”);
s.add(”cc”);
session.setAttribute(”x”, x);
session.setAttribute(”a”, a);
session.setAttribute(”m”, m);
session.setAttribute(”l”, l);
session.setAttribute(”s”, s);
%>
<h4>access values of query parameter p</h4>
<c:if test=”${param.p == null}”>param.p not defined<br /></c:if>
first value: ${param.p}<br />
all values: ${fn:join(paramValues.p,”,”)}

<h4>print objects</h4>
x: ${x}<br />
m: ${m}<br />
s: ${s}<br />
l: ${l}<br />

<h4>print array using join</h4>
a: ${fn:join(a,”,”)}
<br />

<h4>access individuals of array or map via [ ]</h4>
a[1]: ${a[1]}
<br />
m[“bb”]: ${m[“bb”]}
<br />

<h4>access individuals in c:forEach loop</h4>
a: <c:forEach var=”i” items=”${a}”>${i} </c:forEach><br />
s: <c:forEach var=”i” items=”${s}”>${i} </c:forEach><br />
l: <c:forEach var=”i” items=”${l}”>${i} </c:forEach><br />
m: <c:forEach var=”i” items=”${m}”>${i.key}=>${i.value} </c:forEach><br />

<h4>using c:set and escapeXml</h4>
<c:set var=”k” value=”<b>bold</b>” />
k: ${k}<br />
escaped(k): ${fn:escapeXml(k)}<br />
c:out escaped: <c:out value=”${k}” escapeXml=”true” />

<h4>using a bean’s get and set properties indirectly</h4>
mb.count: ${mb.count}:
<c:set target=”${mb}” property=”count” value=”${mb.count + 1}” />
<c:choose>
<c:when test=”${mb.count > 6}”>
became bigger than 6, re-initialize mb
<c:remove var=”mb” />
</c:when>
<c:when test=”${mb.count > 3}”>became bigger than 3</c:when>
<c:otherwise>no more than 3</c:otherwise>
</c:choose>

<h4>User defined tag functions</h4>
s: ${s}<br />
<c:set var=”t” value=”cc” />
s.contains(${t}): ${mtg:contains(s,t)}<br />
<c:set var=”t” value=”dd” />
s.contains(${t}): ${mtg:contains(s,t)}

</body>
</html>
Regards
R.Satish Kumar
JSTL Examples
Select font size:
8pt 9pt 10pt 11pt 12pt 14pt 16pt
Download the

JSTLexamples.war
archive. This archive contains the following files:

index.jsp Script with a variety of examples
bean/MyBean.java User-defined bean example
mytaglib/MyFunctions.java JSTL tag library classes
Functions.tld JSTL tag library definition
Install and run in Eclipse
Prior to starting eclipse, you need to make available two new library JAR files which are included in the apache-tomcat distribution but not available for all applications. Locate the directory:

apache-tomcat-6.0.14/webapps/jsp-examples/WEB-INF/lib/

and within it, the files:

jstl.jar standard.jar

Simply copy these two files into:

apache-tomcat-6.0.14/common/lib/

Then start up eclipse. Follow the steps in JSP Forms import the WAR file JSTLexamples.war and run the project on Tomcat.

The JSP Standard Tag Library (JSTL)
The JSTL library provides a means, through variables, expressions and tags, to avoid the interleaving of Java and tag-style code. Using this language, we can, for the most part, eliminate explicit Java code in JSP pages in favor of augmenting the XML-like tag structure. See

http://jakarta.apache.org/taglibs/
http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/
You should refer to this online documentation:

jstl tld docs
and/or download it yourself:

jstl-1_1-mr2-spec-tlddoc.zip
The standard tags are those described in the table below. We have omitted the sql tags since we don’t plan to use SQL done directly in JSP. Using one of tag groups is effected by the addition of one of the following respective tag statements below.

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

The uri is simply an identifier of the tag set. The prefix is determinable by the user, but the prefixes seen here are standard.

TLD tags and functions c: core fmt: formatting fn: functions x: xml
c:catch
c:choose
c:forEach
c:forTokens
c:if
c:import
c:otherwise
c:out
c:param
c:redirect
c:remove
c:set
c:url
c:when
fmt:bundle
fmt:formatDate
fmt:formatNumber
fmt:message
fmt:param
fmt:parseDate
fmt:parseNumber
fmt:requestEncoding
fmt:setBundle
fmt:setLocale
fmt:setTimeZone
fmt:timeZone
fn:contains()
fn:containsIgnoreCase()
fn:endsWith()
fn:escapeXml()
fn:indexOf()
fn:join()
fn:length()
fn:replace()
fn:split()
fn:startsWith()
fn:substring()
fn:substringAfter()
fn:substringBefore()
fn:toLowerCase()
fn:toUpperCase()
fn:trim()

x:choose
x:forEach
x:if
x:otherwise
x:out
x:param
x:parse
x:set
x:transform
x:when

These and other tag systems are used in JSP in one of two forms:

<tag-prefix:type attribute1=”VALUE1″ …

or, as functions to create expressions:

tag-prefix:function(arg1,arg2,…)

As in XML, tags can be complete, using a single tag ending with “/>“, or in pairs, containing a content terminated by a matching ending tag </tag-prefix:tag-type>. Some example of the common usages of the “c” tags are these:

<c:out value=”…” escapeXml=”true”/>
<c:set var=”x” value=”…” />
<c:if test=”…” > … </c:if>
<c:forEach var=”x” items=”…” > … </c:forEach>

Expression Language (EL)
The syntax for what replaces the “…” above is specified by a Java-like language, unimaginately called Expression Language (EL). EL is part of JSP; its expressions are all surrounded by the syntax ${ }. but typically can only be used most effectively in conjunction with JSTL tags. EL is closely related to Java but has some extensions and conceptual simplifications. In particular, EL is more like other web script languages being loosely typed along with other semantic simplifications. EL expressions permit variables and most of the usual arithmetic and boolean operators. Here are some points:

The == operator for strings functions like the Java .equals operator.
an EL expression with an undefined value, which (normally represented by null in Java) is also represented by null in EL, but is equivalent to the empty string.
EL has a unary operator empty: empty(x) acts like the expression x==null but also means “x equals the empty string”.
the operators or, and are synonyms for ||, &&, respectively.
Query parameters
The value of the parameter “xx” is expressed by the EL expression param.xx. When used directly in HTML,

${param.xx}

is equivalent to the JSP expression:

<%= (request.getParameter(“xx”) != null) ? (request.getParameter(“xx”) : “” %>

Session variables are EL variables
A session variable x automatically becomes available as an EL variable, e.g. if we have:

<%
session.setAttribute( “x”, “hello” );
// or
pageContext.setAttribute( “x”, “hello” );
%>

x = ${x} <!– prints: x = hello — >

JSP beans in JSTL
The EL language provides a simplified syntax for accessing bean’s get/set accessor functions. For example, the bean we use in the examples below is this:

<jsp:useBean id=”mb” class=”bean.MyBean” />

from the class:

——————————————————————————– bean/MyBean.java

package bean;

public class MyBean {
private String count;
public String getCount() { return count; }
public void setCount(String count) { this.count = count; }
public MyBean() {
System.out.println(”MyBean intialized”);
count = “0?;
}
}
EL treats the expression ${mb.count} as the value of mb.getCount(). A typical JSTL tag statement is something like

<c:set var=”i” value=”${mb.count}” />

The c:set tag is also used to call the set member function as follows:

<c:set target=”${mb}” property=”count” value=”5″ />

is equivalent to mb.setCount(”5?). Caution: If you use both set and get property, they must be consistent. For example, suppose you have these member functions:

String getSomeProperty() { … }
void setSomeProperty(int n) { … }

Then EL will consider this a mismatch and most likely reject the setter member function if you tried to use:

<c:set target=”${mb}” property=”someProperty” value=”5″ />

We can also remove a bean from the session using the JSTL c:remove tag:

<c:remove var=”mb” />

Data structures: arrays, arrays, maps, sets
Arrays and maps permit access to their collection via indices: arrays via integer indices and maps via key indices. EL regards both of these accesses as syntactically similar using the [ ] operator. For example:

<%
Map<String,String> theMap = new HashMap<String,String>();
theMap.put(“John”, “5”); theMap.put(“Jim”, “7”);
String theArray[] = { “aaa”, “bbb”, “ccc” };

session.setAttribute( “theMap”, theMap );
session.setAttribute( “theArray”, theArray );
%>

${theMap[“Jim”]} <!– same as theMap.get(”Jim”), outputs 7 –>
${theArray[1]} <!– outputs bbb –>

The EL expressions for maps, sets and lists can all print directly. Arrays, as in Java, don’

t print directly, but must use an auxiliary function. In this case the fn:join function serves the purpose:

${fn:join(theArray,”,”)}

Iterating over data structures
In order to iterate over an array, list, map, or set, the c:forEach tag pair serves our interests. Iteration with c:forEach treats arrays, lists and sets identically. For example, this code will iteratively print the elements:

<!– L represents either an array, list or set –>
<c:forEach var=”x” items=”${L}” >
${x}
</c:forEach>

When using a map, the iteration generates Map.Entry pairs. Using the getKey and getValue functions the structure of the JSTL code to iteratively print the key/value pairs looks like this:

<!– M is a map –>
<c:forEach var=”x” items=”${M}” >
${x.key}: ${x.value}
</c:forEach>

Choice tags c:if, c:choose/c:when
The c:if tag generates a choice situation with a syntax like:

<c:if test=”${EL_BOOLEAN_EXPRESSION}” > … </c:if>

The EL_BOOLEAN_EXPRESSION uses the usual boolean operators with simplifications and additions as mentioned above. If-else structures are based on the c:choose/c:when/c:otherwise tags:

<c:choose>
<c:when test=”${EL_EXPR1}”> … </c:when>
<c:when test=”${EL_EXPR2}”> … </c:when>

<c:otherwise> … </c:otherwise>
</c:choose>

User-generated tag functions
If one wants to avoid explicit JSP sections of code then the Java classes and functions must be able to be accessed through the tag system. Beans provide a limited way of doing so through combinations of “get/set” member functions, but this is not intended for utility functions to manipulate objects. The fn tags provide some of these utility functions, but one can imagine that soon there would be need for your own specific utility functions. Towards this end, JSP provides a means to add your own tag libraries using a combination of Java classes and Tag Library Definition (TLD) files. Both XML-like tags and EL function tags can be added, but it’s much easier to create user-defined EL function tags. The utility functions used must be static functions. For example, suppose we want to use the function defined in this class in an EL expression.

——————————————————————————– mytaglib/MyFunctions.java

package mytaglib;
import java.util.*;
public class MyFunctions {
public static boolean contains(Set<String> set, String target) {
return set.contains(target);
}
}
The glue which connects this functions to JSP is the XML file MyTags.tld held stored in the /WEB-INF/ project directory.

——————————————————————————– MyTags.tld

<?xml version=”1.0? encoding=”UTF-8??>
<taglib version=”2.0? …>
<tlib-version>1.1</tlib-version>
<uri>/WEB-INF/MyTags</uri>
<function>
<name>contains</name>
<function-class>mytaglib.MyFunctions</function-class>
<function-signature>
boolean contains(java.util.Set,java.lang.String)
</function-signature>
</function>
</taglib>
This file defines a uri by which it is accessed and a set of function prototypes in XML format. Each function has a tag name, the class it belongs to and the actual function prototype within this class. The necessary specification within the JSP file is something like this:

<%@taglib prefix=”mtg” uri=”/WEB-INF/MyTags”%>

The prefix chosen specifies how the function will be referenced within the EL syntax — it can be anything you want, so long as it doesn’t conflict with another tag set. In this case the function will be prefaced by mtg: as in this example:

<c:if test=”${mtg:contains(someSet,someValue)}” > … </c:if>

Example script
——————————————————————————– index.jsp

<%@ page language=”java” contentType=”text/html;
charset=US-ASCII” pageEncoding=”US-ASCII”%>

<%@page import=”java.util.*”%>

<%@taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core”%>
<%@taglib prefix=”fn” uri=”http://java.sun.com/jsp/jstl/functions”%>
<%@taglib prefix=”mtg” uri=”/WEB-INF/MyTags”%>

<jsp:useBean id=”mb” scope=”session” class=”bean.MyBean” />

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=US-ASCII”>
<title>Insert title here</title>
<style>
h4 { color: red; margin-bottom:0px; text-decoration: underline; }
</style>
</head>
<body>
<%
String x = “testing”;
String[] a = { “xx”, “yy”, “zz” };

Map<String, String> m = new LinkedHashMap<String, String>();
m.put(”aa”, “1?);
m.put(”bb”, “2?);
m.put(”cc”, “3?);

List<String> l = new ArrayList<String>();
l.add(”nn”);
l.add(”mm”);
l.add(”oo”);
Set<String> s = new LinkedHashSet<String>();
s.add(”aa”);
s.add(”bb”);
s.add(”cc”);
session.setAttribute(”x”, x);
session.setAttribute(”a”, a);
session.setAttribute(”m”, m);
session.setAttribute(”l”, l);
session.setAttribute(”s”, s);
%>
<h4>access values of query parameter p</h4>
<c:if test=”${param.p == null}”>param.p not defined<br /></c:if>
first value: ${param.p}<br />
all values: ${fn:join(paramValues.p,”,”)}

<h4>print objects</h4>
x: ${x}<br />
m: ${m}<br />
s: ${s}<br />
l: ${l}<br />

<h4>print array using join</h4>
a: ${fn:join(a,”,”)}
<br />

<h4>access individuals of array or map via [ ]</h4>
a[1]: ${a[1]}
<br />
m[“bb”]: ${m[“bb”]}
<br />

<h4>access individuals in c:forEach loop</h4>
a: <c:forEach var=”i” items=”${a}”>${i} </c:forEach><br />
s: <c:forEach var=”i” items=”${s}”>${i} </c:forEach><br />
l: <c:forEach var=”i” items=”${l}”>${i} </c:forEach><br />
m: <c:forEach var=”i” items=”${m}”>${i.key}=>${i.value} </c:forEach><br />

<h4>using c:set and escapeXml</h4>
<c:set var=”k” value=”<b>bold</b>” />
k: ${k}<br />
escaped(k): ${fn:escapeXml(k)}<br />
c:out escaped: <c:out value=”${k}” escapeXml=”true” />

<h4>using a bean’s get and set properties indirectly</h4>
mb.count: ${mb.count}:
<c:set target=”${mb}” property=”count” value=”${mb.count + 1}” />
<c:choose>
<c:when test=”${mb.count > 6}”>
became bigger than 6, re-initialize mb
<c:remove var=”mb” />
</c:when>
<c:when test=”${mb.count > 3}”>became bigger than 3</c:when>
<c:otherwise>no more than 3</c:otherwise>
</c:choose>

<h4>User defined tag functions</h4>
s: ${s}<br />
<c:set var=”t” value=”cc” />
s.contains(${t}): ${mtg:contains(s,t)}<br />
<c:set var=”t” value=”dd” />
s.contains(${t}): ${mtg:contains(s,t)}

</body>
</html>