How to use JSTL tags c:forEach, c:if, c:choose and c:catch example


      Click here to attend Spring Framework 4.x and certification course with a discount

If you want to use JSTL core tags inside your web application use the following codes;

First include JSTL standard.jar and jstl.jar inside your web project and create a servlet class for setting attributes used by JSTL tags;

CustomServlet .java

package com.tunatore.servlets;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author tunatore
 */
public class CustomServlet extends HttpServlet {

   /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
        response.setContentType(“text/html;charset=UTF-8”);
        String[] carList = {“SUBARU”,”HONDA”,”TOYOTA”,”SUZUKI”,”VOLCO”,”MERCEDES”};
        request.setAttribute(“carList”, carList);
        request.setAttribute(“username”, “TUNA”);
//forwarding request to resulst.jsp page
        request.getRequestDispatcher(“/result.jsp”).forward(request, response);
}

    // <editor-fold defaultstate=”collapsed” desc=”HttpServlet methods. Click on the + sign on the left to edit the code.”>
    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
@Override
public String getServletInfo() {
return “Short description”;
}// </editor-fold>
}

And create a index.jsp file for forwarding first request to servlet by the following;

<%–
    Document   : index
    Created on : 19.Jun.2011, 19:48:51
    Author     : tunatore
–%>

<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>JSTL Examples</title>
</head>
<body>
<h1>JSTL index</h1>
   <!–this tag will forward request to CustomServlet–>
        <jsp:forward page=”/CustomServlet” />
</body>
</html>

And last create a result.jsp file for testing JSTL core tags;

<%–
    Document   : result
    Created on : 19.Haz.2011, 19:50:24
    Author     : tunatore
–%>
<%@page contentType=”text/html” pageEncoding=”UTF-8″%>
<%@taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core&#8221; %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>
<title>JSTL Examples</title>
</head>
<body bgcolor=”#A9D0F5″>
<h1>JSTL</h1>
<table border=”1″>

<!– c:forEach tag will get carList from the request object and iterate over it–>
            <!– nesting c:forEach tags could be done too–>
<c:forEach var=”car” items=“${carList}”>
<tr>
<td>${car}</td>
</tr>
</c:forEach>
<tr>
<td>
        <!– testing c:if test tag usage –>
        <c:if test=“${username ==’TUNA’}”>
                    Username is –> TUNA c:if test –> WORKED         
         </c:if>
         <!– the following syntax is also true you can use –>
          <!– == (or eq), != (or ne), < (or lt), > (or gt), <= (or le), >= (or ge)–>
          <c:if test=“${username eq ‘OTHERS’}”>
                     Username is –> OTHERS                
          </c:if>    
</td>
</tr>
<tr>
<td>
<!– testing c:choose tag usage –>
       <c:choose>
             <c:when test=“${username eq ‘BILL’}”>
                     Username is –> BILL  
              </c:when>                        
              <c:when test=“${username eq ‘JAMES’}”>
                      Username is –> JAMES  
              </c:when>
              <c:otherwise>
                       Username is –> c:otherwise WORKED! == TRUE  
             </c:otherwise>
     </c:choose>      
</td>
</tr>
<tr>
<td>
<!– testing c:catch tag usage –>
     <c:catch var=“customException”>
           <% int abc = Integer.parseInt(“ABC”);%>                        
      </c:catch>    
       <c:if test=“${customException !=null}”>
             <c:out value=“${customException}”/>                    
       </c:if>
</td>
</tr>
</table>
</body>
</html>

Result of the program;


Download Source

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s