SlideShare a Scribd company logo
Module 5: EL, JSTL and
    Custom Tags


  Thanisa Kruawaisayawan
   Thanachart Numnonda
   www.imcinstitute.com
Objectives

 Expression Language
 JSTL (JSP Standard Tag Library) 1.1
 Custom Tags




                                        2
Expression Language
   EL expressions are ALWAYS within curly braces,
    and prefixed with the dollar sign
        ${firstThing.secondThing}

   firstThing can be
      EL Implicit Object
      Attribute




                                                     3
EL Implicit Object and Attribute

    EL Implicit Object      Attribute
     param                   in page scope
     paramValues
                              in request scope
     header                  in session scope
     headerValues
                              in application scope
       cookie

       initParam

       pageContext

     pageScope
     requestScope
     sessionScope
     applicationScope

                                                      4
EL Implicit Objects
Implicit Object                    Description
 param              Maps of all the form parameters that were
 paramValues        passed to your JSP
 header             Maps of all the request headers
 headerValues
 cookie             A Map of all the cookies passed to your JSP
 initParam          A Map of the context init parameters
 pageScope          A Map of all the objects that have page,
 requestScope       request, session and application scope
 sessionScope
 applicationScope




                                                                  5
hello.html
<form action="helloName.jsp" method="post">
  Name: <input name="username">
   <input type="submit">
</form>




                                              6
param
<%-- helloName.jsp --%>
Hello <%= request.getParameter("username") %><br>
Hello <% out.print(request.getParameter("username"));%><br>
Hello ${param.username}<br>
Hello ${param['username']}<br>
Hello ${param["username"]}<br>




                                                              7
header
Host is ${header.host} <br>
Cookie is ${header.cookie}




                                8
cookie

JSESSIONID = ${cookie.JSESSIONID.value}




                                          9
initParam
//web.xml
<web-app ...>
   :
   <context-param>
        <param-name> driver </param-name>
        <param-value> com.mysql.jdbc.Driver </param-value>
   </context-param>
   :
</web-app>
---------------------------------------------------------------------------
//InitParamEL.jsp
Driver is ${initParam.driver}




                                                                          10
Person.java

package myBeans;

public class Person {
    private String name;
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
}




                                         11
EL and JavaBeans
<jsp:useBean id="personName" class="myBeans.Person" />
<jsp:setProperty name="personName" property="name" value="Thanisa" />

<%-- <jsp:getProperty name="personName" property="name" /> --%>

${personName.name}




                                                                   12
Disable the EL
   For a single page
    <%@ page isELIgnored="true" %>


   For an entire application
    <jsp-property-group>
       <url-pattern>*.jsp</url-pattern>
       <el-enabled>false</el-enabled>
       <scripting-invalid>true</scripting-invalid>
    </jsp-property-group>




                                                     13
The taglib Directive

   Tag libraries come in two different flavors:
       JSTL (JavaServerPages Standard Tag Library)
       Custom Tag Libraries

   The syntax for the taglib directive is as follows:
<%@ taglib uri=“taglibraryURI” prefix=“tagPrefix” %>




                                                         14
JSTL 1.1
   The “Core” library                The “SQL” library
      Looping and Iteration             Database access
             <c:forEach>                      <sql:query>
             <c:forTokens>                    <sql:update>
                                               <sql:setDataSource>
        Conditional                           <sql:param>
             <c:if>                           <sql:dateParam>
             <c:choose>
             <c:when>
             <c:otherwise>
                                      The “Formatting” library
                                                <fmt:message>
        General-purpose                        :
             <c:out>
             <c:remove>
             <c:catch>               The “XML” library
        URL related                           <x:parse>
             <c:import>                            :
             <c:url>
             <c:redirect>
             <c:param>


                                                                      15
Download and copy JSTL Libraries to
             Tomcat




                                      16
Check JSTL in Project




                        17
Core Tag Library
   Looping and Iteration
   Conditional
   General-purpose
   URL related




                                    18
Looping and Iteration
   <c:forEach>
   <c:forTokens>




                                     19
<c:forEach>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<table border="1" align="center">
    <tr bgcolor="orange">
         <th>Header Names and Values</th>
    </tr>
    <c:forEach var="h" items="${header}">
         <tr>
             <td>${h.value}</td>
         </tr>
    </c:forEach>
</table>




                                                                  20
Result




         21
Conditionals

 <c:if>
 <c:choose>, <c:when> and <c:otherwise>




                                           22
Example




          23
poll.html
:
<body>
   <h3>Do you agree with the opposition
        to boycott the election?</h3>
    <form action = "vote.jsp" method = "post">
       <input type=radio name=answer value="Yes"> Yes<br>
       <input type=radio name=answer value="No"> No<br>
       <input type=radio name=answer value="No Comment"> No Comment<br>
       <br><input type=submit value="VOTE">
    </form>
</body>
:




                                                                   24
<c:if>
<%@taglib uri="http://java.sun.com/jsp/jstl/core"
  prefix="c" %>

<c:if test="${param.answer == 'Yes'}" >
    You vote for Yes
</c:if>
<c:if test="${param.answer == 'No'}" >
    You vote for No
</c:if>
<c:if test="${param.answer == 'No Comment'}" >
    You vote for No Comment
</c:if>




                                                    25
<c:choose>, <c:when> and
               <c:otherwise>
<%@taglib uri="http://java.sun.com/jsp/jstl/core"
  prefix="c" %>

<c:choose>
    <c:when test="${param.field == 'Network'}" >
        You choose Network
    </c:when>
    <c:when test="${param.field == 'Database'}" >
        You choose Database
    </c:when>
    <c:otherwise>
        You choose Programming
    </c:otherwise>
</c:choose>



                                                    26
Scoped Variable Manipulation
 <c:out>
 <c:set>
 <c:remove>
 <c:catch>




                                   27
<c:out>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<c:forEach begin="3" end="15" step="3" var="index" varStatus="num">
    <c:out value="${index}" />: <c:out value="${num.count}" /><br>
</c:forEach>




                                                                  28
<c:set> and <c:remove>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<c:set var="status" scope="request" value="On-line" />
Status is ${status} <br>

<c:remove var="status" scope="request" />
Now, status is ${status}




                                                                  29
<c:catch>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

About to do a risky thing <br>
<c:catch var="myException" >
    <% int x = 10/0; %>
</c:catch>
<c:if test="${myException != null}">
    There was an exception: ${myException.message} <br>
</c:if>
If you see this, we survived.




                                                                  30
URL Manipulation
 <c:import>
 <c:redirect>
 <c:url>
 <c:param>




                               31
<c:import>
<%-- Header2.jsp --%>
Information Technology KMITL
-----------------------------------------------------------------
<%-- Test2.jsp --%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:import url="http://localhost:8084/SWP_Topic5/Header2.jsp" />
-----------------------------------------------------------------

  The <c:import> action can also
 be used to specify absolute,
 relative and FTP URL resources
 to provide a lot more functionality
 than the standard <jsp:include> action.
 <c:import> can reach OUTSIDE the
   web app

                                                                    32
<c:redirect>
<%-- Header3.jsp --%>
Information Technology KMITL
-----------------------------------------------------------------
<%-- Test3.jsp --%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:redirect url="http://localhost:8084/SWP_Topic5/Header3.jsp" />
-----------------------------------------------------------------

   The <c:redirect> action simply
    sends an HTTP redirect to
    a client.




                                                                33
<c:url> and <c:param>
<%-- Header4.jsp --%>
${param.faculty}
-----------------------------------------------------------------
<%-- Test4.jsp --%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:url value="http://localhost:8084/SWP_Topic5/Header4.jsp " >
   <c:param name="faculty" value="Information Technology" />
</c:url>
-----------------------------------------------------------------
   The <c:url> action takes care of the encoding and all the URL rewriting.
http://localhost:8084/JSP2/Header.jsp;jsessionid=543ferew432esd23




                                                                               34
SQL Tag Library
 <sql:setDataSource>
 <sql:query>
 <sql:update>
 <sql:param> and <sql:dateParam>
 <sql:transaction>




                                    35
BookStore.jsp
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>

<html>
    <head><title>ABC Book Store </title></head>
    <body>
     <center>
      <form action="BookStore.jsp">
      <h1> ABC Book Store </h1>
      <br> Please select a Book and add it to your shopping cart
      </p>

      <sql:setDataSource var="datasource"
             driver="com.mysql.jdbc.Driver"
   url="jdbc:mysql:///test"                                 user="root"
   password="root" />

      <sql:query var="books" dataSource="${datasource}" >
             select * from books
      </sql:query>



                                                                          36
BookStore.jsp (cont.)
                  <table border="1" align="center">
                     <tr bgcolor="orange">
                       <td>ISBN</td><td>Title</td>
                       <td>Author</td><td>Price</td></tr>
                         <c:forEach var="row" items="${books.rows}">
                         <tr>
                              <td>${row.isbn}</td>
                              <td>${row.title} /></td>
                              <td>${row.author} /></td>
                              <td>${row.price} /></td>
                              <td><input type=submit value="add"></td>
                         </tr>
                     </c:forEach>
                </table>
            </form>
        </center>
    </body>
</html>



                                                                         37
Result




         38
Custom Tag Libraries
 The JSP 1.1 specifications introduced the
  ability to define new tags called custom tags
 Can be used in any number of JSP files
 A user can define how the tag, its attributes
  and its body are to be interpreted, and then
  group these tags into collections, called tag
  libraries.

                                                  39
Simple Tag Files
1.   Take an included file (such as “Header.jsp”) and rename it
     with a .tag extension
        <%-- Header.jsp --%>
        <img src="Duke_Cont.png"><br><br>
        Welcome to Java World!!
1.   Put the tag file (such as “Header.tag”) in a directory named
     “tags” inside the “WEB-INF” directory




1.   Put a taglib directive (with a tagdir atttribute) in the JSP
     (TestTag.jsp)
        <%@taglib tagdir="/WEB-INF/tags" prefix="myTags" %>
        <myTags:Header/>
                                                                    40
Result




         41
Components that make up a Tag library
1.   The Tag Library Descriptor (TLD) file
2.   The Tag Handler class
        Classic
        Simple
1.   The JSP file




                                             42
Repeat Tag Implemented as a
                           Classic JSP 1.2 Tag Extension
                 <%@ taglib prefix="my"
                       uri="/mytags" %>
                 <my:repeat num="3">
Usage




                   tag body
                 </my:repeat>



                 int doStartTag() {
                    this.count = this.num;
Implementation




                    return Tag.EVAL_BODY_INCLUDE;
                 }

                 int doAfterBody() {
                    this.count--;
                    return (this.count > 0) ?
                     Tag.EVAL_BODY_AGAIN :
                     Tag.SKIP_BODY;                        43
                 }
Repeat Tag Implemented as a
                     Simple JSP 2.0 Tag Extension
                 <%@ taglib prefix="my"
                       uri="/mytags" %>
Usage




                 <my:repeat num="3">
                   tag body
                 </my:repeat>



                 void doTag() {
Implementation




                   for( int i = 0; i < num; i++ ) {
                      getJspBody().invoke( null );
                   }
                 }



                                                      44
Create a TLD for the tag




                           45
Making a Simple Tag Handler




                              46
JSP File
   Import the tag library
     Specify    location of TLD file and define a tag
        prefix (namespace)
         <%@ taglib uri="myTaglib" prefix="myPrefix" %>
   Use the tags
       <prefix:tagName />
       Prefix comes from taglib directive
       Tag name comes from tag added into TLD file
       Example <myPrefix:myTag />
                                                          47
Write a JSP that uses the tag
<%-- UseCustomTag.jsp --%>
<%@taglib uri="TestMyTag1" prefix="my" %>
<my:test1/>




                                            48
Thank you

   thananum@gmail.com
www.facebook.com/imcinstitute
   www.imcinstitute.com



                                49

More Related Content

What's hot (20)

PDF
webpack 101 slides
mattysmith
 
PPTX
Laravel Tutorial PPT
Piyush Aggarwal
 
PPT
Customizing Oracle EBS OA Framework
iWare Logic Technologies Pvt. Ltd.
 
PDF
Javascript pour les Développeurs WEB
Abbes Rharrab
 
PPT
jpa-hibernate-presentation
John Slick
 
DOCX
Query to get the geography information using bi report
Feras Ahmad
 
PPT
JPA - Java Persistence API
Rodrigo Cascarrolho
 
PPTX
Using cookies and sessions
Nuha Noor
 
PDF
Oracle Enterprise Scheduler(ESS Job Scheduling)
TUSHAR VARSHNEY
 
PDF
Exception handling
Anna Pietras
 
PDF
Spring Framework - Spring Security
Dzmitry Naskou
 
PPTX
Security: Odoo Code Hardening
Odoo
 
PDF
Chapitre 4 Java script
Manel Ben Sassi
 
ODP
Spring User Guide
Muthuselvam RS
 
DOC
How to create PO with ASN
shravan kumar chelika
 
PDF
Spring Framework - MVC
Dzmitry Naskou
 
PDF
Introduction to SQLAlchemy and Alembic Migrations
Jason Myers
 
PDF
Kotlin coroutines 톺아보기
Taewoo Kim
 
PPTX
Aspect Oriented Programing - Introduction
Venkaiah Chowdary Koneru
 
PDF
Ngrx slides
Christoffer Noring
 
webpack 101 slides
mattysmith
 
Laravel Tutorial PPT
Piyush Aggarwal
 
Customizing Oracle EBS OA Framework
iWare Logic Technologies Pvt. Ltd.
 
Javascript pour les Développeurs WEB
Abbes Rharrab
 
jpa-hibernate-presentation
John Slick
 
Query to get the geography information using bi report
Feras Ahmad
 
JPA - Java Persistence API
Rodrigo Cascarrolho
 
Using cookies and sessions
Nuha Noor
 
Oracle Enterprise Scheduler(ESS Job Scheduling)
TUSHAR VARSHNEY
 
Exception handling
Anna Pietras
 
Spring Framework - Spring Security
Dzmitry Naskou
 
Security: Odoo Code Hardening
Odoo
 
Chapitre 4 Java script
Manel Ben Sassi
 
Spring User Guide
Muthuselvam RS
 
How to create PO with ASN
shravan kumar chelika
 
Spring Framework - MVC
Dzmitry Naskou
 
Introduction to SQLAlchemy and Alembic Migrations
Jason Myers
 
Kotlin coroutines 톺아보기
Taewoo Kim
 
Aspect Oriented Programing - Introduction
Venkaiah Chowdary Koneru
 
Ngrx slides
Christoffer Noring
 

Viewers also liked (6)

ODP
Java Web Programming [1/9] : Introduction to Web Application
IMC Institute
 
PDF
Java and the Web
Dmitry Buzdin
 
PDF
Machine Learning using Apache Spark MLlib
IMC Institute
 
PDF
Mobile User and App Analytics in China
IMC Institute
 
PDF
Thai Software & Software Market Survey 2015
IMC Institute
 
PDF
บทความสรุปงานสัมมนา IT Trends 2017 ของ IMC Institute
IMC Institute
 
Java Web Programming [1/9] : Introduction to Web Application
IMC Institute
 
Java and the Web
Dmitry Buzdin
 
Machine Learning using Apache Spark MLlib
IMC Institute
 
Mobile User and App Analytics in China
IMC Institute
 
Thai Software & Software Market Survey 2015
IMC Institute
 
บทความสรุปงานสัมมนา IT Trends 2017 ของ IMC Institute
IMC Institute
 
Ad

Similar to Java Web Programming [5/9] : EL, JSTL and Custom Tags (20)

PDF
JSP Syntax_1
brecke
 
PPTX
Introduction to JSP
Geethu Mohan
 
PPTX
JSP - Java Server Page
Vipin Yadav
 
PDF
Jsp quick reference card
JavaEE Trainers
 
PDF
JSP Standard Tag Library
Ilio Catallo
 
PDF
Card12
guestd097bc
 
PPTX
JSP.pptx programming guide for beginners and experts
rani marri
 
PDF
03 form-data
snopteck
 
PPT
What is Advance Java J2EE
javaease
 
PPTX
JAVA SERVER PAGES
Kalpana T
 
PPTX
JSP_Complete_Guide_With_Step_By_Step_solution
powerofthehelios
 
PDF
Model-Driven Software Development - Strategies for Design & Implementation of...
Eelco Visser
 
PDF
Strategies for Design & Implementation of Domain-Specific Languages
Eelco Visser
 
PDF
Basic JSTL
corneliuskoo
 
PDF
Lap trinh web [Slide jsp]
Tri Nguyen
 
TXT
Jsp Notes
Rajiv Gupta
 
DOCX
Jsp
parthu310
 
PPTX
JSP- JAVA SERVER PAGES
Yoga Raja
 
PPTX
JSP AND XML USING JAVA WITH GET AND POST METHODS
bharathiv53
 
PDF
10 jsp-scripting-elements
Phạm Thu Thủy
 
JSP Syntax_1
brecke
 
Introduction to JSP
Geethu Mohan
 
JSP - Java Server Page
Vipin Yadav
 
Jsp quick reference card
JavaEE Trainers
 
JSP Standard Tag Library
Ilio Catallo
 
Card12
guestd097bc
 
JSP.pptx programming guide for beginners and experts
rani marri
 
03 form-data
snopteck
 
What is Advance Java J2EE
javaease
 
JAVA SERVER PAGES
Kalpana T
 
JSP_Complete_Guide_With_Step_By_Step_solution
powerofthehelios
 
Model-Driven Software Development - Strategies for Design & Implementation of...
Eelco Visser
 
Strategies for Design & Implementation of Domain-Specific Languages
Eelco Visser
 
Basic JSTL
corneliuskoo
 
Lap trinh web [Slide jsp]
Tri Nguyen
 
Jsp Notes
Rajiv Gupta
 
JSP- JAVA SERVER PAGES
Yoga Raja
 
JSP AND XML USING JAVA WITH GET AND POST METHODS
bharathiv53
 
10 jsp-scripting-elements
Phạm Thu Thủy
 
Ad

More from IMC Institute (20)

PDF
นิตยสาร Digital Trends ฉบับที่ 14
IMC Institute
 
PDF
Digital trends Vol 4 No. 13 Sep-Dec 2019
IMC Institute
 
PDF
บทความ The evolution of AI
IMC Institute
 
PDF
IT Trends eMagazine Vol 4. No.12
IMC Institute
 
PDF
เพราะเหตุใด Digitization ไม่ตอบโจทย์ Digital Transformation
IMC Institute
 
PDF
IT Trends 2019: Putting Digital Transformation to Work
IMC Institute
 
PDF
มูลค่าตลาดดิจิทัลไทย 3 อุตสาหกรรม
IMC Institute
 
PDF
IT Trends eMagazine Vol 4. No.11
IMC Institute
 
PDF
แนวทางการทำ Digital transformation
IMC Institute
 
PDF
บทความ The New Silicon Valley
IMC Institute
 
PDF
นิตยสาร IT Trends ของ IMC Institute ฉบับที่ 10
IMC Institute
 
PDF
แนวทางการทำ Digital transformation
IMC Institute
 
PDF
The Power of Big Data for a new economy (Sample)
IMC Institute
 
PDF
บทความ Robotics แนวโน้มใหม่สู่บริการเฉพาะทาง
IMC Institute
 
PDF
IT Trends eMagazine Vol 3. No.9
IMC Institute
 
PDF
Thailand software & software market survey 2016
IMC Institute
 
PPTX
Developing Business Blockchain Applications on Hyperledger
IMC Institute
 
PDF
Digital transformation @thanachart.org
IMC Institute
 
PDF
บทความ Big Data จากบล็อก thanachart.org
IMC Institute
 
PDF
กลยุทธ์ 5 ด้านกับการทำ Digital Transformation
IMC Institute
 
นิตยสาร Digital Trends ฉบับที่ 14
IMC Institute
 
Digital trends Vol 4 No. 13 Sep-Dec 2019
IMC Institute
 
บทความ The evolution of AI
IMC Institute
 
IT Trends eMagazine Vol 4. No.12
IMC Institute
 
เพราะเหตุใด Digitization ไม่ตอบโจทย์ Digital Transformation
IMC Institute
 
IT Trends 2019: Putting Digital Transformation to Work
IMC Institute
 
มูลค่าตลาดดิจิทัลไทย 3 อุตสาหกรรม
IMC Institute
 
IT Trends eMagazine Vol 4. No.11
IMC Institute
 
แนวทางการทำ Digital transformation
IMC Institute
 
บทความ The New Silicon Valley
IMC Institute
 
นิตยสาร IT Trends ของ IMC Institute ฉบับที่ 10
IMC Institute
 
แนวทางการทำ Digital transformation
IMC Institute
 
The Power of Big Data for a new economy (Sample)
IMC Institute
 
บทความ Robotics แนวโน้มใหม่สู่บริการเฉพาะทาง
IMC Institute
 
IT Trends eMagazine Vol 3. No.9
IMC Institute
 
Thailand software & software market survey 2016
IMC Institute
 
Developing Business Blockchain Applications on Hyperledger
IMC Institute
 
Digital transformation @thanachart.org
IMC Institute
 
บทความ Big Data จากบล็อก thanachart.org
IMC Institute
 
กลยุทธ์ 5 ด้านกับการทำ Digital Transformation
IMC Institute
 

Recently uploaded (20)

PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
POV_ Why Enterprises Need to Find Value in ZERO.pdf
darshakparmar
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 

Java Web Programming [5/9] : EL, JSTL and Custom Tags

  • 1. Module 5: EL, JSTL and Custom Tags Thanisa Kruawaisayawan Thanachart Numnonda www.imcinstitute.com
  • 2. Objectives  Expression Language  JSTL (JSP Standard Tag Library) 1.1  Custom Tags 2
  • 3. Expression Language  EL expressions are ALWAYS within curly braces, and prefixed with the dollar sign ${firstThing.secondThing}  firstThing can be  EL Implicit Object  Attribute 3
  • 4. EL Implicit Object and Attribute  EL Implicit Object  Attribute  param  in page scope  paramValues  in request scope  header  in session scope  headerValues  in application scope  cookie  initParam  pageContext  pageScope  requestScope  sessionScope  applicationScope 4
  • 5. EL Implicit Objects Implicit Object Description param Maps of all the form parameters that were paramValues passed to your JSP header Maps of all the request headers headerValues cookie A Map of all the cookies passed to your JSP initParam A Map of the context init parameters pageScope A Map of all the objects that have page, requestScope request, session and application scope sessionScope applicationScope 5
  • 6. hello.html <form action="helloName.jsp" method="post"> Name: <input name="username"> <input type="submit"> </form> 6
  • 7. param <%-- helloName.jsp --%> Hello <%= request.getParameter("username") %><br> Hello <% out.print(request.getParameter("username"));%><br> Hello ${param.username}<br> Hello ${param['username']}<br> Hello ${param["username"]}<br> 7
  • 8. header Host is ${header.host} <br> Cookie is ${header.cookie} 8
  • 10. initParam //web.xml <web-app ...> : <context-param> <param-name> driver </param-name> <param-value> com.mysql.jdbc.Driver </param-value> </context-param> : </web-app> --------------------------------------------------------------------------- //InitParamEL.jsp Driver is ${initParam.driver} 10
  • 11. Person.java package myBeans; public class Person { private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } } 11
  • 12. EL and JavaBeans <jsp:useBean id="personName" class="myBeans.Person" /> <jsp:setProperty name="personName" property="name" value="Thanisa" /> <%-- <jsp:getProperty name="personName" property="name" /> --%> ${personName.name} 12
  • 13. Disable the EL  For a single page <%@ page isELIgnored="true" %>  For an entire application <jsp-property-group> <url-pattern>*.jsp</url-pattern> <el-enabled>false</el-enabled> <scripting-invalid>true</scripting-invalid> </jsp-property-group> 13
  • 14. The taglib Directive  Tag libraries come in two different flavors:  JSTL (JavaServerPages Standard Tag Library)  Custom Tag Libraries  The syntax for the taglib directive is as follows: <%@ taglib uri=“taglibraryURI” prefix=“tagPrefix” %> 14
  • 15. JSTL 1.1  The “Core” library  The “SQL” library  Looping and Iteration  Database access  <c:forEach>  <sql:query>  <c:forTokens>  <sql:update>  <sql:setDataSource>  Conditional  <sql:param>  <c:if>  <sql:dateParam>  <c:choose>  <c:when>  <c:otherwise>  The “Formatting” library  <fmt:message>  General-purpose :  <c:out>  <c:remove>  <c:catch>  The “XML” library  URL related  <x:parse>  <c:import> :  <c:url>  <c:redirect>  <c:param> 15
  • 16. Download and copy JSTL Libraries to Tomcat 16
  • 17. Check JSTL in Project 17
  • 18. Core Tag Library  Looping and Iteration  Conditional  General-purpose  URL related 18
  • 19. Looping and Iteration  <c:forEach>  <c:forTokens> 19
  • 20. <c:forEach> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <table border="1" align="center"> <tr bgcolor="orange"> <th>Header Names and Values</th> </tr> <c:forEach var="h" items="${header}"> <tr> <td>${h.value}</td> </tr> </c:forEach> </table> 20
  • 21. Result 21
  • 22. Conditionals  <c:if>  <c:choose>, <c:when> and <c:otherwise> 22
  • 23. Example 23
  • 24. poll.html : <body> <h3>Do you agree with the opposition to boycott the election?</h3> <form action = "vote.jsp" method = "post"> <input type=radio name=answer value="Yes"> Yes<br> <input type=radio name=answer value="No"> No<br> <input type=radio name=answer value="No Comment"> No Comment<br> <br><input type=submit value="VOTE"> </form> </body> : 24
  • 25. <c:if> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <c:if test="${param.answer == 'Yes'}" > You vote for Yes </c:if> <c:if test="${param.answer == 'No'}" > You vote for No </c:if> <c:if test="${param.answer == 'No Comment'}" > You vote for No Comment </c:if> 25
  • 26. <c:choose>, <c:when> and <c:otherwise> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <c:choose> <c:when test="${param.field == 'Network'}" > You choose Network </c:when> <c:when test="${param.field == 'Database'}" > You choose Database </c:when> <c:otherwise> You choose Programming </c:otherwise> </c:choose> 26
  • 27. Scoped Variable Manipulation  <c:out>  <c:set>  <c:remove>  <c:catch> 27
  • 28. <c:out> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <c:forEach begin="3" end="15" step="3" var="index" varStatus="num"> <c:out value="${index}" />: <c:out value="${num.count}" /><br> </c:forEach> 28
  • 29. <c:set> and <c:remove> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <c:set var="status" scope="request" value="On-line" /> Status is ${status} <br> <c:remove var="status" scope="request" /> Now, status is ${status} 29
  • 30. <c:catch> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> About to do a risky thing <br> <c:catch var="myException" > <% int x = 10/0; %> </c:catch> <c:if test="${myException != null}"> There was an exception: ${myException.message} <br> </c:if> If you see this, we survived. 30
  • 31. URL Manipulation  <c:import>  <c:redirect>  <c:url>  <c:param> 31
  • 32. <c:import> <%-- Header2.jsp --%> Information Technology KMITL ----------------------------------------------------------------- <%-- Test2.jsp --%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <c:import url="http://localhost:8084/SWP_Topic5/Header2.jsp" /> -----------------------------------------------------------------  The <c:import> action can also be used to specify absolute, relative and FTP URL resources to provide a lot more functionality than the standard <jsp:include> action.  <c:import> can reach OUTSIDE the web app 32
  • 33. <c:redirect> <%-- Header3.jsp --%> Information Technology KMITL ----------------------------------------------------------------- <%-- Test3.jsp --%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <c:redirect url="http://localhost:8084/SWP_Topic5/Header3.jsp" /> -----------------------------------------------------------------  The <c:redirect> action simply sends an HTTP redirect to a client. 33
  • 34. <c:url> and <c:param> <%-- Header4.jsp --%> ${param.faculty} ----------------------------------------------------------------- <%-- Test4.jsp --%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <c:url value="http://localhost:8084/SWP_Topic5/Header4.jsp " > <c:param name="faculty" value="Information Technology" /> </c:url> -----------------------------------------------------------------  The <c:url> action takes care of the encoding and all the URL rewriting. http://localhost:8084/JSP2/Header.jsp;jsessionid=543ferew432esd23 34
  • 35. SQL Tag Library  <sql:setDataSource>  <sql:query>  <sql:update>  <sql:param> and <sql:dateParam>  <sql:transaction> 35
  • 36. BookStore.jsp <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %> <html> <head><title>ABC Book Store </title></head> <body> <center> <form action="BookStore.jsp"> <h1> ABC Book Store </h1> <br> Please select a Book and add it to your shopping cart </p> <sql:setDataSource var="datasource" driver="com.mysql.jdbc.Driver" url="jdbc:mysql:///test" user="root" password="root" /> <sql:query var="books" dataSource="${datasource}" > select * from books </sql:query> 36
  • 37. BookStore.jsp (cont.) <table border="1" align="center"> <tr bgcolor="orange"> <td>ISBN</td><td>Title</td> <td>Author</td><td>Price</td></tr> <c:forEach var="row" items="${books.rows}"> <tr> <td>${row.isbn}</td> <td>${row.title} /></td> <td>${row.author} /></td> <td>${row.price} /></td> <td><input type=submit value="add"></td> </tr> </c:forEach> </table> </form> </center> </body> </html> 37
  • 38. Result 38
  • 39. Custom Tag Libraries  The JSP 1.1 specifications introduced the ability to define new tags called custom tags  Can be used in any number of JSP files  A user can define how the tag, its attributes and its body are to be interpreted, and then group these tags into collections, called tag libraries. 39
  • 40. Simple Tag Files 1. Take an included file (such as “Header.jsp”) and rename it with a .tag extension <%-- Header.jsp --%> <img src="Duke_Cont.png"><br><br> Welcome to Java World!! 1. Put the tag file (such as “Header.tag”) in a directory named “tags” inside the “WEB-INF” directory 1. Put a taglib directive (with a tagdir atttribute) in the JSP (TestTag.jsp) <%@taglib tagdir="/WEB-INF/tags" prefix="myTags" %> <myTags:Header/> 40
  • 41. Result 41
  • 42. Components that make up a Tag library 1. The Tag Library Descriptor (TLD) file 2. The Tag Handler class  Classic  Simple 1. The JSP file 42
  • 43. Repeat Tag Implemented as a Classic JSP 1.2 Tag Extension <%@ taglib prefix="my" uri="/mytags" %> <my:repeat num="3"> Usage tag body </my:repeat> int doStartTag() { this.count = this.num; Implementation return Tag.EVAL_BODY_INCLUDE; } int doAfterBody() { this.count--; return (this.count > 0) ? Tag.EVAL_BODY_AGAIN : Tag.SKIP_BODY; 43 }
  • 44. Repeat Tag Implemented as a Simple JSP 2.0 Tag Extension <%@ taglib prefix="my" uri="/mytags" %> Usage <my:repeat num="3"> tag body </my:repeat> void doTag() { Implementation for( int i = 0; i < num; i++ ) { getJspBody().invoke( null ); } } 44
  • 45. Create a TLD for the tag 45
  • 46. Making a Simple Tag Handler 46
  • 47. JSP File  Import the tag library  Specify location of TLD file and define a tag prefix (namespace) <%@ taglib uri="myTaglib" prefix="myPrefix" %>  Use the tags  <prefix:tagName />  Prefix comes from taglib directive  Tag name comes from tag added into TLD file  Example <myPrefix:myTag /> 47
  • 48. Write a JSP that uses the tag <%-- UseCustomTag.jsp --%> <%@taglib uri="TestMyTag1" prefix="my" %> <my:test1/> 48
  • 49. Thank you [email protected] www.facebook.com/imcinstitute www.imcinstitute.com 49