Friday, June 5, 2015

JSTl Important Tags

JSTL out tag

JSTL out tag is used to display information on JSP. It can also be used with properties of the bean.

JSTL c out tag Example:

To display the name of the product on JSP, you can use the <c:out> tag like:

<c:out value="${product.name}" default="Not Available" escapeXml="true"></c:out>

The above statement assumes that product object is available on this JSP and that product bean has a property name with setters and getters.
Attributes of <c:out> tag are:
   Required Attributes:
       1. value:This attribute needs expression to be evaluated.
  Optional Attributes:
       1. default: This attribute provides default value if the resulting value is null.
       2. escapeXml: This attribute determines whether characters &,'," in the resulting string should be converted to their corresponding character entity codes. Default value is set to true.

JSTL forEach Tag

JSTL forEach tag is used to iterate over the collection. It can be List, Set, ArrayList, HashMap or any other collection.
JSTL forEach Example:
To display the name of the product on JSP, you can use the <c:forEach> tag like:

<c:forEach items="${productList}" var="product" varStatus="status">
    <c:out value="${product.name}" default="Not Available" escapeXml="false"></c:out>
  </c:forEach>

The above statement assumes that productList object is available on this JSP and that product bean has a property name with setters and getters.
As you can see above, in the JSTL forEach tag, items attirbute is used to define the collection. It will iterate over productList. In each iteration, it will get a product variable defined with attribute var. status attirbute keeps track of iteration.
Withing starting and ending tag of forEach, you can display or apply other logic to each object in the collection. As shown in the above example, product name is displayed with index using c:out tag
Attributes of JSTL forEach tag are:
    1. items:This attribute provides collection of items to iterate over.
     2. var: This attribute provides name of the exported scoped variable for the current item of the iteration. This scoped variable has nested visiblity. Its type depends on the object of the underlying collection.
     3. varStatus: This attribute provides name of the exported scoped variable for the status of the iteration. Object exported is of type javax.servlet.jsp.jstl.core.LoopTagStatus. This scoped variable has nested visibility.
     4. begin: If items specified: Iteration begins at the item located at the specified index. First item of the collection has index 0. If items not specified: Iteration begins with index set at the value specified.
     5. end: If items specified: Iteration ends at the item located at the specified index (inclusive). If items not specified: Iteration ends when index reaches the value specified.
    6. step: Iteration will only process every step items of the collection, starting with the first one.
Iterate over HashMap:
Let's take another example which many people face during coding of real web application. Many times you get HashMap and need to iterate over it. In the example below, I take Map of Country Code and Currency, where country code is unique and selected as a key and currency is a value.

<c:forEach items="${countryCurrencyMap}" var="entry" varStatus="status>
    <c:out value="${entry.key}"> : <c:out value="${entry.value}">
 </c:forEach>

JSTL Set Tag

JSTL Set tag is used to create new variable and assign a value to new or existing variable. 

JSTL Set Tag Example,
 <c:set var="weight" value="10.05"/>
 <c:out value="${weight}"/> 

As you can see above, in the set tag, new variable "weight" is created and value is set to 10.05. In the next line, it prints the valued of weight variable using out tag.

JSTL IF Tag

JSTL c:if tag is used as a conditional statement in JSP. It is similar like If statement in JAVA. Based on condition evaluation within test attribute, if tag decides to run the code within JSTL IF tag

  <c:if test="${weight > 0}"/>
         <c:out value="${weight}"/>
     </c:if>

As you can see above, in the JSTL c:if tag, test attribute check the condition and if condition returns true, it executes the other statements within <c:if> and </c:if> statement.

JSTL If Else Statement Example

Like JAVA, JSTL has if statement. However, JSTL do not have if else statement like JAVA. JSTL provides same functionality using choose-when-otherwise statement. These tags are used as a conditional statement in JSP.
In this tutorial, you will see examples for both JSTL If statement and JSTL if else statement ( using choose-when-otherwise  statement ). 
JSTL c:if tag example:
Assume that you have a variable weight in your application. It is available in pound. You want to convert it to Kilograms. However you want to convert it only, if it is available and not null. You can use c:if tag in this case.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
              "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSTL If Tag Example</title>
</head>

<body>

<c:set var="weight" value="10">
 <c:if test="${weight != null}">
 Weight of the product is ${weight * 0.453592} kgs. 
 <c:if> 
</body>
</html> 


Output: Weight of the product is 4.53592 kgs.
As you can see above, <c:if> tag in JSTL is similar to if statement in JAVA.
JSTL if else tag example:
Let's continue with same example shown above where you have a variable weight of the product available in pound and you want to convert it to Kilograms. However you want to show different messages for different condition.
If weight is null, you want to display "Weight is not provided for this product."
If weight is negative, you want to display "Incorrect weight. It can not be negative."
If weight is zero, you want to display "Incorrect weight. It can not be zero."
If weight is not null and above zero, you want to display "Weight of the product is XXXX kgs."
In this case you want to use if else statement in JAVA. But in JSTL, you can use c:choose - c:when - c:otherwiser tag.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
              "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSTL If Tag Example</title>
</head>
<body>

    Scenario 1:
    <!--Weight is not available-->
    <c:choose>
        <c:when test="${weight == null}">
             Weight is not provided for this product.
        </c:when>
        <c:when test="${weight <= 0}">
             Incorrect weight. It can not be zero or negative.
        </c:when>
        <c:otherwise>
             Weight of the product is <c:out value="${weight}"/> lbs.
        <c:otherwise/>
    </c:choose>

   Scenario 2:
    <!--Weight is available but negative value-->
    <c:set var="weight" value="-6">
    <c:choose>
        <c:when test="${weight == null}">
             Weight is not provided for this product.
        </c:when>
        <c:when test="${weight <= 0}">
             Incorrect weight. It can not be zero or negative.
        </c:when>
        <c:otherwise>
             Weight of the product is <c:out value="${weight}"/> lbs.
        <c:otherwise/>
    </c:choose>

   Scenario 3:
    <!--Weight is available but zero value-->
    <c:set var="weight" value="0">
    <c:choose>
        <c:when test="${weight == null}">
             Weight is not provided for this product.
        </c:when>
        <c:when test="${weight <= 0}">
             Incorrect weight. It can not be zero or negative.
        </c:when>
        <c:otherwise>
             Weight of the product is <c:out value="${weight}"/> lbs.
        <c:otherwise/>
    </c:choose>

  Scenario 4:
    <!--Weight is available and it is 10 lbs.-->
    <c:set var="weight" value="10">
    <c:choose>
        <c:when test="${weight == null}">
             Weight is not provided for this product.
</c:when>
        <c:when test="${weight <= 0}">
             Incorrect weight. It can not be zero or negative.
        </c:when>
        <c:otherwise>
             Weight of the product is <c:out value="${weight}"/> lbs.
        <c:otherwise/>
    </c:choose>
    
</body> 
</html>


Output: 
Scenario 1:Weight is not provided for this product.
Scenario 2:Incorrect weight. It can not be negative..
Scenario 3:Incorrect weight. It can not be zero.
Scenario 4:Weight of the product is 4.53592 kgs.
Make sure that there is no condition evaluation in <c:choose> block. This is enclosing tag for <c:when> and <c:otherwise> blocks.
<c:when> tag has condition evaluation capability and you can have multiple <c:when> blocks within single <c:choose> block. Each condition can be evaluated using test attribute of this statement.
<c:otherwise> block do not have any condition evaluation capabiity. It represents all conditions which are not covered by <c:when> statements. <c:otherwise> statement must be present in <c:choose> block.

JSTL Choose When Otherwise Tag

These tags are used as a conditional statement in JSP. 

For Example,
 <c:choose>
          <c:when test="${weight > 0}">
              <c:out value="${weight}"/>
          </c:when>
          <c:otherwise>
              <c:out value="0"/>
          <c:otherwise/>
      </c:choose>

As you can see above, <c:choose>-<c:when>-<c:otherwise> tags JSP are similar to if-elesif-else blocks in JAVA. When you have multiple conditions and each of them produces different output, you can use <c:choose>-<c:when>-<c:otherwise>.
Make sure that there is no codition eveluation in <c:choose> block. This is enclosing tag for <c:when> and <c:otherwise> blocks.
<c:when> tag has condition evaluation capability and you can have multiple <c:when> blocks within single <c:choose> block. Each condition can be evaluated using test attribute of this statement.
<c:otherwise> block do not have any condition evaluation capabiity. It represents all conditions which are not covered by <c:when> statements. <c:otherwise> statement must be present in <c:choose> block.
JSTL Catch TagJSTL catch tag is used to catch the exception thrown at run time in JSP.

<c:catch var="exception">

    <c:out value="${firstNumber/ secondNumber}"/> 

  </c:catch>

  <c:if test="${exception != null}">

    Exception thrown is <c:out value="${exception}"/> 

  </c:if>

As you can see above, we are trying to display result of dividing firstNumber with secondNumber. It may be possible that secondNumber is 0. In that event, exception will be thrown at run time. <c:catch> block will handle this exception and print the exception in the next <c:if> block.

JSTL Remove Tag

Remove tag is being used in JSP to remove the variable from the scope.

 <c:set var="price" value="10.0" scope="session">
    <c:out value="${price}"/>
    <c:remove var="price">
    <c:out value="${price}"/>
As you can see above, <c:set> tag creates a new variable price with value of 10.0 and having scope for the current session. When tag <c:out> is used to print the value, first time it will print 10.0
In line 3, <c:remove> tag is removing the variable price from the session scope. In line 4, when <c:out> tag is printing value of variable price, it will not print anything as it is removed in line 2.

C:Import
JSTL Import tag is being used in JSP to include the content of other resource in the current JSP.

<c:import url="http://www.apekshit.com" var="tutorial" />
 <c:out value="${tutorial}"/> 

As you can see above, <c:import> tag imports the content of another resource specified in url attribute to the current JSP. It store the content to variable tutorial and prints it using <c:out> tag in the next line.
The <c:import> tag is similar to import action in JSP. However, <c:import> can import resouces from other applications also by providing absolute path to it.

<c:forTokens

  <c:forTokens delims=" {,}" items="{25,50,75,100}" var="number">
    <c:out value="${number}" default="25"></c:out>
  </c:forTokens>

Required Attributes:
      1. items:This attribute provides string of tokens to iterate over..
       2. delims: This attribute provides the set of delimiters. The characters that separate the tokens in the string.
Optional Attributes:
       1. var: This attribute provides name of the exported scoped variable for the current item of the iteration. This scoped variable has nested visiblity. Its type depends on the object of the underlying collection.
       2. varStatus: This attribute provides name of the exported scoped variable for the status of the iteration. Object exported is of type javax.servlet.jsp.jstl.core.LoopTagStatus. This scoped variable has nested visibility.
       3. begin: If items specified: Iteration begins at the item located at the specified index. First item of the collection has index 0. If items not specified: Iteration begins with index set at the value specified.
      4. end: If items specified: Iteration ends at the item located at the specified index (inclusive). If items not specified: Iteration ends when index reaches the value specified.
     5. step: Iteration will only process every step items of the collection, starting with the first one.

No comments:

Post a Comment