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

DOCX
Tags list of html and css
Abdul Wahab Raza
 
PPTX
JSP- JAVA SERVER PAGES
Yoga Raja
 
PPT
CSS
Sunil OS
 
PDF
You Don't Know Query (WordCamp Netherlands 2012)
andrewnacin
 
DOCX
Html viva questions
Vipul Naik
 
PDF
The JavaScript Programming Language
guestceb98b
 
PPT
Intro Html
Chidanand Byahatti
 
PDF
HTML Dasar : #5 Heading
Sandhika Galih
 
Tags list of html and css
Abdul Wahab Raza
 
JSP- JAVA SERVER PAGES
Yoga Raja
 
CSS
Sunil OS
 
You Don't Know Query (WordCamp Netherlands 2012)
andrewnacin
 
Html viva questions
Vipul Naik
 
The JavaScript Programming Language
guestceb98b
 
Intro Html
Chidanand Byahatti
 
HTML Dasar : #5 Heading
Sandhika Galih
 

What's hot (20)

ODP
Introduction to jQuery
manugoel2003
 
PDF
HTML Dasar : #6 List
Sandhika Galih
 
PDF
Java servlets
Mukesh Tekwani
 
PPTX
HTML Attributes.pptx
Steins18
 
PPS
PHP Security
manugoel2003
 
PDF
Django Templates
Willy Liu
 
PDF
HTML Dasar : #7 Hyperlink
Sandhika Galih
 
PDF
Web technology lab manual
neela madheswari
 
PPT
HTML 5 Tables and Forms
Doncho Minkov
 
KEY
HTML presentation for beginners
jeroenvdmeer
 
PPT
Pertemuan 05
Andyy EmeMezt
 
PDF
Handlebars.js
Ivano Malavolta
 
PPT
JavaScript: Events Handling
Yuriy Bezgachnyuk
 
PPTX
Introduction to HTML
Ajay Khatri
 
PDF
HTML Dasar : #8 Image
Sandhika Galih
 
PPTX
Html forms
nobel mujuji
 
PPTX
Html vs xhtml
Yastee Shah
 
PDF
Intro to Php Security
Dave Ross
 
PPTX
Javascript 101
Shlomi Komemi
 
PDF
CSS Selectors
Rachel Andrew
 
Introduction to jQuery
manugoel2003
 
HTML Dasar : #6 List
Sandhika Galih
 
Java servlets
Mukesh Tekwani
 
HTML Attributes.pptx
Steins18
 
PHP Security
manugoel2003
 
Django Templates
Willy Liu
 
HTML Dasar : #7 Hyperlink
Sandhika Galih
 
Web technology lab manual
neela madheswari
 
HTML 5 Tables and Forms
Doncho Minkov
 
HTML presentation for beginners
jeroenvdmeer
 
Pertemuan 05
Andyy EmeMezt
 
Handlebars.js
Ivano Malavolta
 
JavaScript: Events Handling
Yuriy Bezgachnyuk
 
Introduction to HTML
Ajay Khatri
 
HTML Dasar : #8 Image
Sandhika Galih
 
Html forms
nobel mujuji
 
Html vs xhtml
Yastee Shah
 
Intro to Php Security
Dave Ross
 
Javascript 101
Shlomi Komemi
 
CSS Selectors
Rachel Andrew
 
Ad

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
Strategies for Design & Implementation of Domain-Specific Languages
Eelco Visser
 
PDF
Model-Driven Software Development - Strategies for Design & Implementation of...
Eelco Visser
 
PDF
Basic JSTL
corneliuskoo
 
PDF
Lap trinh web [Slide jsp]
Tri Nguyen
 
TXT
Jsp Notes
Rajiv Gupta
 
DOCX
Jsp
parthu310
 
PPTX
JSP AND XML USING JAVA WITH GET AND POST METHODS
bharathiv53
 
PDF
10 jsp-scripting-elements
Phạm Thu Thủy
 
PPS
Jsp element
kamal kotecha
 
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
 
Strategies for Design & Implementation of Domain-Specific Languages
Eelco Visser
 
Model-Driven Software Development - Strategies for Design & Implementation of...
Eelco Visser
 
Basic JSTL
corneliuskoo
 
Lap trinh web [Slide jsp]
Tri Nguyen
 
Jsp Notes
Rajiv Gupta
 
JSP AND XML USING JAVA WITH GET AND POST METHODS
bharathiv53
 
10 jsp-scripting-elements
Phạm Thu Thủy
 
Jsp element
kamal kotecha
 

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)

PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
Beyond Automation: The Role of IoT Sensor Integration in Next-Gen Industries
Rejig Digital
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PDF
Architecture of the Future (09152021)
EdwardMeyman
 
PPTX
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PDF
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
PDF
Software Development Company | KodekX
KodekX
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
Beyond Automation: The Role of IoT Sensor Integration in Next-Gen Industries
Rejig Digital
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
Architecture of the Future (09152021)
EdwardMeyman
 
Comunidade Salesforce São Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira Júnior
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
Software Development Company | KodekX
KodekX
 

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