JDev

Code, jstlFebruary 21, 2008 8:56 pm

The JSTL iterator exposes  a varStatus variable that holds the loop status. With this information at hand, we can constuct the following JSTL loop to create a list with alternate colors.

<ul>
        <c:forEach var="row" items="${queryResults.rowsByIndex}" varStatus=’vs’>
                 <c:choose>
                 <c:when test= "${vs.index % 2 == 0}">
                         <li class=’even’>
                 </c:when>
                 <c:otherwise>       
                     <li>
                  </c:otherwise>
                  </c:choose>
                       <c:out value="${row[0]}"/>                    
                 </li>
        </c:forEach>
     </ul>

The test condition checks whether the index property of varStatus variable is even or odd, and assigns a css class named ‘even’ to each even item.

You can easily substitute table rows for li elements in this example.

Code, jstlDecember 5, 2007 6:55 pm

JSTL has a set of pre-defined objects such as  pageScope, requestScope, param, paramValues and cookie.

 If you have a cookie named ‘myCookie’, you can obtain its value as follows:

<c:out value="${cookie.myCookie.value}"/>

 

 

Code, jstlMay 9, 2007 12:12 pm

To get session values in JSTL, use the following piece of code:

<c:forEach items="${sessionScope}" var="par">
        Session object name/value : <c:out value="${par.key} - ${par.value}"/>
</c:forEach>

 To find out how to sort session or request parameters, visit http://www.ekcsoft.com/coding/java/jstl_parameters  

JSTL Books on Amazon.com 


 
Code, jstlMarch 21, 2007 1:56 pm

Here is an JSTL code example that shows how to build a select box that remembers the previous selection.

<select name=’days‘>
      <c:forTokens items="7;14;30;60;180; 365" delims=";" var="current">             
          <c:choose>
            <c:when test="${current==param.days}">
                      <OPTION selected>
                 </c:when>            
                 <c:otherwise>
                       <OPTION>
                 </c:otherwise>
             </c:choose>
               <c:out value="${current}" /></option>       
         </c:forTokens>
 </select>

Each iteration checks an option value against a request parameter that contains the value of the selected option element. If they are equal, the HTML option tag is given a selected attribute.

JSTL Books on Amazon.com 

Code, jstl 1:03 pm

Here is a simple example that shows how to populate Javascript array values from JSTL iteration tags:

<script type=’text/javascript’>
    var arr = new Array();
    <c:forEach begin="1" end="5" var="current">
        arr.push(<c:out value="${current}" />);
    </c:forEach>   
</script>

The Javascript arr array now contains values from 1 to 5.

JSTL Books on Amazon.com

Code, jstlOctober 26, 2006 12:15 pm

It’s very easy to concatenate strings and combine expressions in JSTL.

Here is an example

<c:set var="query" value="${nextAction}?item=${param.item}"/>

Anything not enclosed in ${…} is treated like a literal, and expressions inside the curly brackets are evaluated. So if ${nextAction} has the value of "viewCart.do" and ${param.item} has the value of "1234", the value of the query variable will be as follows:

viewCart.do?item=1234

Also, you can concatenate a variable to itself as follows:

<c:set var=’myVar’ value=’myValue’>
<c:set var=’myVar’ value= ‘${myVar} and some other value’ />

 This can be useful if you deal with iterations. An example:

<c:forTokens var="token" delims=":" items="a:b:c:d:e">
         <c:set var=’myVar‘ value=’${myVar} ${token} and’ />           
</c:forTokens>

<c:out value=’${myVar}’/> outputs ‘a and b and c and d and e and‘.

You can skip the last iteration using the varStatus variable:

<c:forTokens var="token" delims=":" items="a:b:c:d:e" varStatus=’vs‘>     
         <c:set var=’where’ value=’${where} workorder_id = ${token}’ />            
         <c:if test = "${!vs.last}">            
             <c:set var=’myVar’ value=’${myVar} ${token} and’ /> 
        </c:if>            
</c:forTokens>

 

Visit http://www.ekcsoft.com/coding/java/jstl_parameters to learn how to display and sort all request parameters with JSTL.

 

jstl, javaAugust 31, 2006 7:50 pm

There is a problem with using JSTL to show text data that was previously saved from a textarea. If you show such text data in a table, the line-breaks from the textarea will be ignored and the text will be hard to read. A possible solution is to use a Java bean to process such data and replace line-breaks with BR tags before showing it on the page. Such a bean may look as follows:

package beans;
public class HTMLBreaker {
   
    private String text;  
    public HTMLBreaker() {               
    } 
   
    private  String insertBreaks(String text){      
        int len = text.length();      
        StringBuffer sb = new StringBuffer(len+16);          
        for(int i=0; i<text.length();i++){       
            if(text.charAt(i)==’\n’)           
                sb.append("<br>");           
            else       
                sb.append(text.charAt(i));   
        }           
        return sb.toString();       
    }   
   
   
    public String getText() {
        return text;
    }

    public void setText(String string) {
         text="";
        if(string != null)
            text = insertBreaks(string);         
    }
}

 

Then, on a JSP page create  the bean instance:

    <jsp:useBean id=’hbreaker’ class=’beans.HTMLBreaker’>

Set the bean property with the value of a database field: 

     <c:set target=’${hbreaker}’ property=’text’ value=’${row.text}’/>

Display the modified value of the bean property on the page:  

   <jsp:getProperty name=’hbreaker’ property=’text’/>          

If you use the JSTL c:out tag:

<c:out value=’${hbreaker.text}’/>

the BR tags surrounding symbols will be replaced with HTML characters, and show up as such on the screen.                                       

Don’t forget to close the bean tag:

  </jsp:useBean> 

A couple of other solutions using the JSTL fn:replace function and the Jakarta String Tag Library are offered at this weblog.

 

Code, jstl 2:03 pm

This web page has a concise description of how to set and access java bean properties from JSTL.

Briefly, to initialize a bean and set its properties, use the following example:

<jsp:useBean id=’beanIdclass=’className’>
    <c:set target=’${beanId}’ property=’propName’ value=’${someValue}’/>
</jsp:useBean>

To get a bean property value:

    <c:out value=’${beanId.propName}’/>

Code, jstlAugust 30, 2006 12:39 pm

After you execute a JSTL query, the result set is assigned to the scoped var variable as an instance of the javax.servlet.jsp.jstl.sql.Result interface. This object provides properties for accessing the rows, column names, and size of the query’s result set:

Property Description
rows An array of SortedMap objects, each of which maps column names to a single row in the result set
rowsByIndex An array of arrays, each corresponding to a single row in the result set
columnNames An array of strings naming the columns in the result set, in the same order as used for the rowsByIndex property
rowCount The total number of rows in the query result
limitedByMaxRows True if the query was limited by the value of the maxRows attribute

Some usage examples as requested in the first comment to the blog:

First of all, you have to set up a data source, e.g. to connect to an Oracle database:

    <sql:setDataSource var="dataSrc"
       url="jdbc:oracle:thin:@127.0.0.1:1521:database_name"
       driver="oracle.jdbc.driver.OracleDriver"
       user="user_name" password="pass_word"/>

Then you run a query:

   <sql:query var="queryResults" dataSource="${dataSrc}">

        select system_id, employeename from employees

   </sql:query>
 Then, you display the results on the web page:

<table>
     <tr>
       <th>ID</th>
       <th>Name</th>
     </tr>
   <c:forEach var="row" items="${queryResults.rows}">
     <tr>    
       <td>   
          <c:out value="${row.system_id}"/>
       </td>
       <td><c:out value="${row.employeename}"/></td>
     </tr>
   </c:forEach>    
   </table>
 

This is as simple an example as you can get. The bottom line is that when you use the rows property, you refer to values by column names.

Here is an example that uses rowsByIndex property:

<c:forEach var="row" items="${queryResults.rowsByIndex}">
   <tr>    
       <td>   
          <c:out value="${row[0]}"/>
       </td>
       <td><c:out value="${row[1]}"/></td>
     </tr>
</c:forEach>     
 
Same resultset, you just refer to column values by the column index property.
   
The next example shows how to use the columnNames property:
      
<table>
     <tr>
       <th><c:out value="${queryResults.columnNames[0]}"/></th>
       <th><c:out value="${queryResults.columnNames[1]}"/></th>
     </tr>
    …
   </table>
    
 In this case, the table headings will be  system_id and employeename.
 
 The rowCount property is self-evident. It shows the number of rows returned by your query:

          <c:out value="${queryResults.rowCount}"/>

  
 You use the limitedByMaxRows property if you used the maxRows attribute in your query:
 
<sql:query var="queryResults" dataSource="${dataSrc}"
                    maxRows="20">
In this case, the resultset will contain only 20 rows.              

 <c:if test="${queryResults.limitedByMaxRows}">
                Your query returned too many rows.
</c:if>

   The limitedByMaxRows propery can be used for pagination purposes.
  

Now, I will show how to get to display a resultset from any sql statement. The resulting table will display field names as column headings. This code is pretty generic.

    <table>      
     <tr>
         <c:forEach var="columnName" items="${queryResults.columnNames}">
            <th><c:out value="${columnName}"/></th>
          </c:forEach>
      </tr>
    <c:forEach var="row" items="${queryResults.rows}">
          <tr>
              <c:forEach var="columnName" items="${queryResults.columnNames}">
                <td><c:out value="${row[columnName]}"/></td>
             </c:forEach>           
         </tr>
     </c:forEach>     
    </table>      

Visit this page to learn how to display and sort request parameters with  JSTL.

Code, jstlJuly 20, 2006 4:43 pm

The JSTL sql:param tag is real handy to use inside the sql:query tag to supply parameters for sql statements like the following:

    <sql:query var="result">
        SELECT ORDER
        FROM ORDERS
        WHERE CUSTOMER_ID= ?
       <sql:param value=’${param.id}’/>
</sql:query>

However, if you need to use the LIKE condition, the sql:param won’t work. The solution is to use the c:out tag followed by a percentage sign:

  <sql:query var="result">
        SELECT ORDER
        FROM ORDERS
        WHERE YEAR LIKE ‘<c:out value="${param.year}"/>%’
</sql:query>

 

Code, jstlJuly 4, 2006 7:57 pm

The simplest way to format a date type field in JSTL is to use a formatDate tag. Example:

<fmt:formatDate value="${row[1]}"/>

 This will display a date value in the default format which is MMM-D-YYYY on my Windows XP machine. You can use various attributes such as dateStyle, timeStyle and pattern to customize the date display format.

You can use any of the values default, short, medium, long, or full for the dateStyle attribute.

 This is how you format both date and time using the current date:

 <jsp:useBean id="now" class="java.util.Date" />
 Date : <fmt:formatDate type="both" value="${now}" dateStyle="medium" timeStyle="short"/>
 

A pattern example:

<fmt:formatDate pattern="MMM dd yyyy, HH:mm:ss" value="${row[1]}"/>

In a similar fashion, it’s very easy to format a number as currency in JSTL. Example:

<fmt:formatNumber value="${row[2]}" type="currency"/> 

 One of the best books on JSTL is written by Shawn Bayern, the reference implementation lead for JSTL.
 

jstl 7:18 pm

    With JSTL it is easy to display query results on a web page. Most online tutorials list code similar to the following:

<sql:query var="queryResults" dataSource="${dataSrc}">
    select * from employees
</sql:query>
 

<c:forEach var="row" items="${queryResults.rows}">

     <c:out value="${row.id}"/>
    <c:out value="${row.lastname"/>

</c:forEach>
 

What if you want to display table values referring to the multiple array which is the result set by column index instead of column name. You should use the following syntax:

  <c:out value="${row [0]}"/>
  <c:out value="${row [1]}"/>

However, it is not enough. When you use the forEach tag, you should also use rowsByIndex property of the Result object as follows: 

<c:forEach var="row" items="${queryResults.rowsByIndex}">   

Only then your jsp will be valid and will not throw an exception. 

jstlFebruary 28, 2006 8:26 pm

This JSTL post moved to http://www.ekcsoft.com/jstl/content/paginate/