Chapter9 using JSTL

JSTL is not part of JSP 2.0 spec. (jstl.jar & standard.jar copy needed)

(*) <c:out>

<c:out value='${pageContent.currentTip}' escapeXml="true" default="No tip" />
  • escapeXML: when true, escapes HTML special characters (<,>,&,’,”) and default value is true.
  • default: attribute is to show default value when the value attribute data is null. Or default value can be defined in the body.

(*) <c:forEach>

<c:forEach var="movie" items="${movieList}" varStatus="info">
	<tr><td>${info.count}</td><td>${movie}</td></tr>
</c:forEach>
  • Items: array, collection, map, comma delimited string
  • varStatus: extra object that you can get count information.
  • <c:forEach> can be nested.

(*) <c:if>

<c:if test="${userType eq 'member'}" >
	<jsp:include page="input.jsp" />
</c:if>

(*) <c:choose>, <c:when>, <c:otherwise>

<c:choose>
	<c:when test="${userPref == 'performance'}" >
		…
	</c:when>
	<c:when test="${userpref == 'safety'}" >
		…
	</c:when>
	<c:otherwise> … </c:otherwise>  
 
</c:choose>

<c:otherwise> is not a mandatory item within <c:choose>

(*) <c:set >

  1. Setting attribute variable ‘var’
    <c:set var="userlevel" scope="session" value="admin" />

    When the attribute ‘userlevel’ does not exist, it will create one within the session scope only if value is not null.

    • Scope : it is optional. Default is page scope
    • Value : it may not be string. It can be object defined using EL ${object}

    <c:set var="userlevel" scope="session">admin</c:set>
    *Using data in the body as the value when body is used.

    *If value is null, the var is removed even if it was previously defined!

  2. using ‘target’ Setting target for Map and Bean object. (Not for array and list)
    <c:set target="${PetMap}" property="dogName" value="Clover" />

    If the target expression is null, container throws exception.
    Target should be the actual object. So do no use ID names(string) but EL expression to reference real object.
    Even if target object exists, but propery name does not, Exception will be thrown.

(*) <c:remove>

<c:remove var="userStatus" scope="request" />

The var must be string , can’t be an expression.
If scope not defined, the named attribute is removed from all scopes.

(*) <c:import>

<c:import url=http://www.yahoo.com/index.html />

This tag can import outside url page. <c:import> support local and remote file.

It is similar to <jsp:import> & <jsp:param> . But <jsp:import> supports only local file.

<c:import url="include.jsp" >
	<c:param name="subtitle" value="This is subtitle" />
</c:import>

If the URL is local resource , the <c:param> will be available as local variable in the local resource.
If the URL is remote website, the <c:param> value will be passed as query string.

(*) <c:redirect>

<c:redirect url=http://www.yahoo.com" >
	<c:param name="query_name" value="query_value" />
</c:redirect>

Same as reponse.sendRedirect(”…”); Client Redirect.

(*) <c:url>

<c:url value="/output.jsp"  var="tempUrl" />

Just like encodeURL(), this element adds jsessionid to the URL if cookie is disabled.
The actual url is stored into Var name and it is used to refer to the actual URL at the bottom of jsp page.

<c:url value="/test.jsp" >
	<c:param name="firstname" value="${first}" />
	<c:param name="lastname" value="${last}" />
</c:url>

In order to encode the query string, you need to use <c:param> on each name and value pair. (not like encodeURL())

(*) Error page

<%@ page isErrorPage ="true" > says this page is only used to show when error occurs. This makes exception implicit object available (scriplet ==> exception object , EL ==> ${pageContext.exception} )
<%@ page errorPage =”errorPage.jsp”> If error occurs in this JSP page, forward to the error page.

DD

<error-page>
	<exception-type>java.lang.Throwable</exception-type> <!-- Throwable catch means to catch all exception-->
	<location>/errorPage.jsp</location>
</error-page>
<error-page>
	<error-code>404</error-code>
	<location>/404page.jsp</location>
</error-page>

You can make the exception an attribute with in the same JSP page

<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>

(*) Custom Tag Library

TLD FILE: /WEB-INF/anyname.tld (the file extension must be tld)

<?xml version="1.0" encoding="ISO-8859-1" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version="2.0">
	<tlib-version>1.2</tlib-version>  <!--mandatory-->
	<short-name>MyTagTests</short-name> <!--mandatory-->
<uri>MyTagTests</uri>  <!--mandatory-->
	<tag>
		<description>Simple Test</description> <!-- optional -->
		<name>SimpleTest</name> <!-- require -->
		<tag-class>com.example.web.tag.TestSimpleTag</tag-class> <!-- Required -->
		<body-content>scriptless</body-content> <!-- required! -->
		<attribute>  <!-- attribute tag is required for each attribute needed -->
			<name>arg1</name>			
			<required>true</required>
			<rtexprvalue>true</rtexprvalue>
		</attribute>		
</tag>	
</taglib>

JSP FILE: /tagusing.jsp

<%@ taglib prefix="mytag" uri="MyTagTests" %>

The uri should be the actual tld file path (/WEB-INF/anyname.tld) or the <uri> element name from the tld file.

<mytag:SimpleTest arg1="${value}" >
	Here is the body
</mytag:SimpleTest>
  • using the prefix defined in the taglib.
  • Attribute name is defined in the <attribute> . If <required> is true and you didn’t use the attribute , you get Exception.
  • Body is used since <body-content> is not empty. If <body-content> is empty but body exists, you get Exception.

Actual tag class java source (simple tag): /WEB-INF/classes/com/example/web/tag/TestSimpleTag.class

package com.example.web.tag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;
 
public class TestSimpleTag extends SimpleTagSupport {
    private String arg1;
 
    @override
    public void doTag() throws JspException, IOException { //must be overriden
        // Write something to output
        String result="Body is empty";
        JspFragment jf = getJspBody();
        if (jf != null ){
            jf.invoke(null); // evaluating the tag body
            result="Body is not empty!";
        }
        getJspContext().getOut().println("<br>ARG: "+this.arg1 + "<br>" + result);	
    }
 
    public void setArg1(String arg){  //Create a setter method for each Attribute
        this.arg1=arg;
    }
}

* Tag file <rtexprvalue> true ==> means OK to use both EL and scripting Expression.
The default value is false for <rtexprvalue>. When you use EL when <rtexprvalue>=false, you get exception.

Below three tags are all the same.

<mytag:SimpleTest arg1="${name}" />
<mytag:SimpleTest arg1="<%=request.getAttribute("name")%>" />
<mytag:SimpleTest >
	<jsp:attribute name="arg1">${name}</jsp:attribute>
</mytag:SimpleTest>

<jsp:attribute> can be used inside of tag body for tag’s each attribute.

*Values for <body-content>

  • empty: tag must not have body
  • scriptless: no scriptlets allowed, but EL, customs and standard tags are OK.
  • tagdependent: body treated as plain text
  • JSP : All is allowed

* <uri> is just a name , not a location!

* You had to define taglib in the OLD DD specification

<taglib>
	<taglib-uri>MyTagTests</taglib-uri>
	<taglib-location>/WEB-INF/anyname.tld</taglib-location>
</taglib>

* You can’t use below prefix in taglib directive : jsp, jspx, java, javax, servlet, sun, sunw

(*) Next: [SCWCD] Cram Sheet 7 - Custom Tag Development



One Response to “[SCWCD] Cram Sheet 6 - using JSTL”

  1.   Remember the code? » Blog Archive » [SCWCD] Cram Sheet 5 - scriptless JSP Says:

    [...] Next: [SCWCD] Cram Sheet 6 - using JSTL Posted by HanaDaddy Filed in java Tags: java, SCWCD [...]

Leave a Reply