SlideShare a Scribd company logo
JEE - JSTL, Custom Tags and
Maven
Fahad R. Golra
ECE Paris Ecole d'Ingénieurs - FRANCE
Lecture 4 - JSTL, Custom Tags
& Maven
• JSTL
• MVC
• Tag Libraries
• Custom Tags
• Basic Tags with/without body
• Attributes in custom tags
• Maven
2 JEE - JSTL, Custom Tags & Maven
Best practices
• Modularity
• Separation of concerns
• Loose-coupling
• Abstraction
• Encapsulation
• Reuse
3 JEE - JSTL, Custom Tags & Maven
Web Application Development
• Model-View-Controller (MVC) Architecture
• Model
• Business objects or domain objects
• POJOs & JavaBeans
• View
• Visual representation of model
• JSP, JSF
• Controller
• Navigation Flow & Model-view integration
• Servlets
4 JEE - JSTL, Custom Tags & Maven
JavaBeans [Model]
• Must follow JavaBeans Conventions
• Public Default Constructor (no parameter)
• Accessor methods for a property p of Type T
• GET: public T getP()
• SET: public void setP(T)
• IS: public boolean isP()
• Persistence - Object Serialization
• JavaBean Conventions:
http://docstore.mik.ua/orelly/java-ent/jnut/ch06_02.htm
5 JEE - JSTL, Custom Tags & Maven
JavaBean Example (Recall)
package com.ece.jee;
public class PersonBean implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String firstName = null;
private String lastName = null;
private int age = 0;
public PersonBean() {
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}6
JavaBean Example (Recall)
public int getAge() {
return age;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setAge(Integer age) {
this.age = age;
}
}
7
JSP [View]
• Best practice goals
• Minimal business logic
• Reuse
• Design options
• JSP + Standard Action Tags + JavaBeans
• JSP + Standard Actions + JSTL + JavaBeans
8 JEE - JSTL, Custom Tags & Maven
JSTL
• Conceptual extension to JSP Standard Actions
• XML tags
• Supports common structural tasks such as
iterations and conditions, tags for manipulating
XML documents, internationalization tags, and SQL
tags.
• JSP Standard Tag Library
• Defined as Java Community Process
• Custom Tag Library mechanism (discuss soon)
• Available within JSP/Servlet containers
9 JEE - JSTL, Custom Tags & Maven
JSTL Library
• JSTL is installed in most common Application Servers
like JBoss, Glassfish etc.
• Note: Not provided by Tomcat
• Installation in Tomcat
• Download from https://jstl.java.net/download.html
• Drag the JSTL API & Implementation jars in the /WEB-INF/lib
folder of eclipse project.
10 JEE - JSTL, Custom Tags & Maven
Example using scriptlet
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Count to 10 using JSP scriptlet</title>
</head>
<body>
<% for (int i = 1; i <= 10; i++) { %>
<%=i%>
<br />
<% } %>
</body>
</html>
11
Example using JSTL
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Count to 10 using JSTL</title>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
</head>
<body>
<c:forEach var="i" begin="1" end="10" step="1">
<c:out value="${i}" />
<br />
</c:forEach>
</body>
</html>
12
The JSTL Tag Libraries
• Core Tags
• Formatting Tags
• SQL Tags
• XML Tags
• JSTL Functions
13 JEE - JSTL, Custom Tags & Maven
Tag Library Prefix & URI
14 JEE - JSTL, Custom Tags & Maven
Library URI Prefix
Core http://java.sun.com/jsp/jstl/core c
XML Processing http://java.sun.com/jsp/jstl/xml x
Formatting http://java.sun.com/jsp/jstl/fmt fmt
Database Access http://java.sun.com/jsp/jstl/sql sql
Functions http://java.sun.com/jsp/jstl/functions fn
<%@taglib prefix= c uri= http://java.sun.com/
jsp/jstl/core %>
where to find the Java class or tag file that
implements the custom action
which elements are part of a custom tag library
Core Tag Library
• Contains structural tags that are essential to nearly all
Web applications.
• Examples of core tag libraries include looping,
expression evaluation, and basic input and output.
• Syntax:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
15 JEE - JSTL, Custom Tags & Maven
Core Tag Library
16
Tag! Description !
<c:out >! Like <%= ... >, but for expressions. !
<c:set >! Sets the result of an expression evaluation in a
'scope'!
<c:remove >! Removes a scoped variable (from a particular scope,
if specified). !
<c:catch>! Catches any Throwable that occurs in its body and
optionally exposes it.!
<c:if>! Simple conditional tag which evalutes its body if the
supplied condition is true.!
<c:choose>! Simple conditional tag that establishes a context for
mutually exclusive conditional operations, marked by
<when> and <otherwise> !
<c:when>! Subtag of <choose> that includes its body if its
condition evalutes to 'true'.!
Core Tag Library
17
Tag! Description !
<c:otherwise >! Subtag of <choose> that follows <when> tags and
runs only if all of the prior conditions evaluated to
'false'.!
<c:import>! Retrieves an absolute or relative URL and exposes its
contents to either the page, a String in 'var', or a
Reader in 'varReader'.!
<c:forEach >! The basic iteration tag, accepting many different
collection types and supporting subsetting and other
functionality .!
<c:forTokens>! Iterates over tokens, separated by the supplied
delimeters.!
<c:param>! Adds a parameter to a containing 'import' tag's URL.!
<c:redirect >! Redirects to a new URL.!
<c:url>! Creates a URL with optional query parameters!
• Catches an exception thrown by JSP elements in its
body
• The exception can optionally be saved as a page
scope variable
• Syntax:
<c:catch>
JSP elements
</c:catch>
18 JEE - JSTL, Custom Tags & Maven
<c: catch>
• only the first <c:when> action that evaluates to true is
processed
• if no <c:when> evaluates to true <c:otherwise> is
processed, if exists
• Syntax:
<c:choose>
1 or more <c:when> tags and optionally a
<c:otherwise> tag
</c:choose>
19 JEE - JSTL, Custom Tags & Maven
<c: choose>
• Evaluates its body once for each element in a
collection
– java.util.Collection, java.util.Iterator, java.util.Enumeration,
java.util.Map
– array of Objects or primitive types
• Syntax:
<c:forEach items=“collection” [var=“var”]
[varStatus=“varStatus”] [begin=“startIndex”]
[end=“endIndex”] [step=“increment”]>
JSP elements
</c:forEach>
20 JEE - JSTL, Custom Tags & Maven
<c: forEach>
• Evaluates its body once for each token n a string
delimited by one of the delimiter characters
• Syntax:
<c:forTokens items=“stringOfTokens”
delims=“delimiters” [var=“var”]
[varStatus=“varStatus”] [begin=“startIndex”]
[end=“endIndex”] [step=“increment”]>
JSP elements
</c:forTokens>
21 JEE - JSTL, Custom Tags & Maven
<c: forTokens>
• Evaluates its body only if the specified expression is
true
• Syntax1:
<c:if test=“booleanExpression”
var=“var” [scope=“page|request|session|
application”] />
• Syntax2:
<c:if test=“booleanExpression” >
JSP elements
</c:if>
22 JEE - JSTL, Custom Tags & Maven
<c: if>
• imports the content of an internal or external resource
like <jsp:include> for internal resources however,
allows the import of external resources as well (from a
different application OR different web container)
• Syntax:
<c:import url=“url” [context=“externalContext”]
[var=“var”] [scope=“page|request|session|
application”] [charEncoding=“charEncoding”]>
Optional <c:param> actions
</c:import>
23 JEE - JSTL, Custom Tags & Maven
<c: import>
• Nested action in <c:import> <c:redirect> <c:url> to
add a request parameter
• Syntax 1:
<c:param name=“parameterName”
value=“parameterValue” />
• Syntax 2:
<c:param name=“parameterName”>
parameterValue
</c:param>
24 JEE - JSTL, Custom Tags & Maven
<c: param>
• Adds the value of the evaluated expression to
the response buffer
• Syntax 1:
<c:out value=“expression” [excapeXml=“true|
false”] [default=“defaultExpression”] />
• Syntax 2:
<c:out value=“expression” [excapeXml=“true|
false”]>
defaultExpression
</c:out>
25 JEE - JSTL, Custom Tags & Maven
<c: out>
• Sends a redirect response to a client telling it to make a
new request for the specified resource
• Syntax 1:
<c:redirect
url=“url” [context=“externalContextPath”]
/>
• Syntax 2:
<c:redirect
url=“url” [context=“externalContextPath”]
> <c:param> tags
</c:redirect>
26 JEE - JSTL, Custom Tags & Maven
<c: redirect>
• removes a scoped variable
• if no scope is specified the variable is removed from
the first scope it is specified
• does nothing if the variable is not found
• Syntax:
<c:remove var=“var” [scope=“page|request|session|
application”] />
27 JEE - JSTL, Custom Tags & Maven
<c: remove>
• sets a scoped variable or a property of a target object
to the value of a given expression
• The target object must be of type java.util.Map or a
Java Bean with a matching setter method
• Syntax 1:
<c:set value=“expression” target=“beanOrMap”
property=“propertyName” />
• Syntax 2:
<c:set value=“expression” var=“var” scope=“page|
request|session|application” />
28 JEE - JSTL, Custom Tags & Maven
<c: set>
• applies encoding and conversion rules for a relative or
absolute URL
– URL encoding of parameters specified in <c:param> tags
– context-relative path to server-relative path
– add session Id path parameter for context- or page-relative
path
• Syntax:
<c:url url=“url” [context=“externalContextPath”]
[var=“var”] scope=“page|request|session|
application” >
<c:param> actions
</c:url>
29 JEE - JSTL, Custom Tags & Maven
<c: url>
Formatting Tag Library
• Contains tags that are used to parse data.
• Some of these tags will parse data, such as dates,
differently based on the current locale.
• Syntax:
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
30 JEE - JSTL, Custom Tags & Maven
Formatting Tag Library
31 JEE - JSTL, Custom Tags & Maven
Tag Description
<fmt:formatNumber> To render numerical value with specific precision or
format.
<fmt:parseNumber> Parses the string representation of a number,
currency, or percentage.
<fmt:formatDate> Formats a date and/or time using the supplied styles
and pattern
<fmt:parseDate> Parses the string representation of a date and/or
time
<fmt:bundle> Loads a resource bundle to be used by its tag body.
<fmt:setLocale> Stores the given locale in the locale configuration
variable.
Formatting Tag Library
32 JEE - JSTL, Custom Tags & Maven
Tag Description
<fmt:formatNumber> To render numerical value with specific precision or
format.
<fmt:parseNumber> Parses the string representation of a number,
currency, or percentage.
<fmt:formatDate> Formats a date and/or time using the supplied styles
and pattern
<fmt:parseDate> Parses the string representation of a date and/or
time
<fmt:bundle> Loads a resource bundle to be used by its tag body.
<fmt:setLocale> Stores the given locale in the locale configuration
variable.
Database Tag Library
• Contains tags that can be used to access SQL
databases.
• These tags are normally used to create prototype
programs only. This is because most programs will
not handle database access directly from JSP pages.
• Syntax:
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
33 JEE - JSTL, Custom Tags & Maven
Database Tag Library
34 JEE - JSTL, Custom Tags & Maven
Tag Description
<sql:setDataSource> Creates a simple DataSource suitable only for
prototyping
<sql:query> Executes the SQL query defined in its body or
through the sql attribute.
<sql:update> Executes the SQL update defined in its body or
through the sql attribute.
<sql:param> Sets a parameter in an SQL statement to the
specified value.
<sql:dateParam> Sets a parameter in an SQL statement to the
specified java.util.Date value.
<sql:transaction > Provides nested database action elements with a
shared Connection, set up to execute all statements
as one transaction.
XML Tag Library
• Contains tags that can be used to access XML
elements.
• XML is used in many Web applications, XML
processing is an important feature of JSTL.
• Syntax:
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
35 JEE - JSTL, Custom Tags & Maven
XML Tag Library
36 JEE - JSTL, Custom Tags & Maven
Tag Description
<x:out> Like <%= ... >, but for XPath expressions.
<x:parse>
Use to parse XML data specified either via an
attribute or in the tag body.
<x:set > Sets a variable to the value of an XPath expression.
<x:if >
Evaluates a test XPath expression and if it is true, it
processes its body. If the test condition is false, the
body is ignored.
<x:forEach> To loop over nodes in an XML document.
XML Tag Library
37 JEE - JSTL, Custom Tags & Maven
Tag Description
<x:choose>
Simple conditional tag that establishes a context
for mutually exclusive conditional operations,
marked by <when> and <otherwise>
<x:when >
Subtag of <choose> that includes its body if its
expression evalutes to 'true'
<x:otherwise >
Subtag of <choose> that follows <when> tags and
runs only if all of the prior conditions evaluated to
'false'
<x:transform > Applies an XSL transformation on a XML document
<x:param >
Use along with the transform tag to set a
parameter in the XSLT stylesheet
JSTL Functions
• JSTL includes a number of standard functions, most
of which are common string manipulation functions.
• Syntax:
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"
%>
38 JEE - JSTL, Custom Tags & Maven
JSTL Functions
39
Function Description
fn:contains() Tests if an input string contains the specified substring.
fn:containsIgnoreCase() Tests if an input string contains the specified substring in a
case insensitive way.
fn:endsWith() Tests if an input string ends with the specified suffix.
fn:escapeXml() Escapes characters that could be interpreted as XML markup.
fn:indexOf() Returns the index within a string of the first occurrence of a
specified substring.
fn:join() Joins all elements of an array into a string.
fn:length() Returns the number of items in a collection, or the number of
characters in a string.
fn:replace() Returns a string resulting from replacing in an input string all
occurrences with a given string.
fn:split() Splits a string into an array of substrings.
Custom Tags
• User defined JSP language elements
(as opposed to standard tags)
• Encapsulates recurring tasks
• Distributed in a “custom made” tag
library
40 JEE - JSTL, Custom Tags & Maven
Why use custom tags?
• Custom tags can be used for
• Generating content for a JSP page
• Accessing a page’s JavaBeans
• Introducing new JavaBeans
• Introducing new scripting variables
• Using the strength of Java
41 JEE - JSTL, Custom Tags & Maven
Custom Tag Syntax
• Like the standard actions, custom tags follow XML
syntax conventions
<prefix:name attribute=”value” attribute=”value”/>


<prefix:name attribute=”value” attribute=”value”>

body content

</prefix:name>
42 JEE - JSTL, Custom Tags & Maven
Custom tags architecture
• Custom tag architecture is made up of:
• Tag handler class
• Defines tag's behaviour
• Tag library descriptor (TLD)
• Maps XML elements to tag handler class
• JSP file (user of custom tags)
• Uses tags
43 JEE - JSTL, Custom Tags & Maven
Tag Handlers
• A tag handler class must implement one of the following interfaces:
• javax.servlet.jsp.tagext.Tag
• javax.servlet.jsp.tagext.IterationTag
• javax.servlet.jsp.tagext.BodyTag
• Usually extends utility class
• javax.servlet.jsp.tagext.TagSupport
• javax.servlet.jsp.tagext.BodyTagSupport
• javax.servlet.jsp.tagext.SimpleTagSupport
• Located in the same directory as servlet class files
• Tag attributes are managed as JavaBeans properties (i.e., via getters
and setters)
44 JEE - JSTL, Custom Tags & Maven
Tag Library Descriptor
• Defines tag syntax and maps tag names to
handler classes
• Specifies tag attributes
• Attribute names and optional types
• Required vs. optional
• Compile-time vs. run-time values
• Specifies tag variables (name, scope, etc.)
• Declares tag library validator and lifecycle
event handlers, if any
45 JEE - JSTL, Custom Tags & Maven
How to implement, use & deploy
• Four steps to follow:
• write tag handlers
• write so called tag library descriptor (TLD) file
• package a set of tag handlers and TLD file into tag
library
• write JSP pages that use these tags. Then you deploy
the tag library along with JSP pages.
• Syntax to use custom Tags in JSP is same as JSTL
<%@ taglib prefix="myprefix" uri=”myuri” %>
46 JEE - JSTL, Custom Tags & Maven
Example: HelloTag.java
package com.ece.jee;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class HelloTag extends SimpleTagSupport {
public void doTag() throws JspException, IOException {
JspWriter out = getJspContext().getOut();
out.println("Hello, I am body-less Custom Tag!");
}
}
47
Example: custom.tld
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.1"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://
java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
>
<tlib-version>1.0</tlib-version>
<short-name>ex</short-name>
<uri>http://jee.ece.com</uri>
<tag>
<name>Hello</name>
<tag-class>com.ece.jee.HelloTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
48
Example: hello.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="ex" uri="http://jee.ece.com"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>A sample custom tag</title>
</head>
<body>
<ex:Hello />
</body>
</html>
49
Custom Tags with Body
• The <body-content> specifies what type of content is
allowed
• empty - no nested content
• sriptless - text, EL & JSP without sriptlets & expressions
• JSP - Everything allowed in JSP
• tagdependent - tag evaluates itself
<tag>
<name>Hello</name>
<tag-class>com.ece.jee.HelloTag</tag-class>
<body-content>empty</body-content>
</tag>
50 JEE - JSTL, Custom Tags & Maven
Custom Tags with Body
package com.ece.jee;
import java.io.IOException;
import java.io.StringWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class HelloBodyTag extends SimpleTagSupport {
StringWriter sw = new StringWriter();
public void doTag() throws JspException, IOException {
getJspBody().invoke(sw);
getJspContext().getOut().println(sw.toString());
}
}
51
Custom Tags with Body
• custom.tld
<tag>
<name>HelloBody</name>
<tag-class>com.ece.jee.HelloBodyTag</tag-class>
<body-content>scriptless</body-content>
</tag>
• hello.jsp
<body>
<ex:Hello />
<br/>
<ex:HelloBody>
Hello! I am a custom Tag with body
</ex:HelloBody>
</body>
52
Custom Tags with attributes
public class HelloAttributeTag extends TagSupport {
private static final long serialVersionUID = 1L;
private String message;
public void setMessage(String msg) {
this.message = msg;
}
@Override
public int doStartTag() throws JspException {
JspWriter out = pageContext.getOut();
if (message != null) {
try {
out.println(message);
} catch (IOException e) {
e.printStackTrace();
}
}
return SKIP_BODY;
}
}
53
Custom Tags with attributes
• custom.tld
<tag>
<name>HelloAttribute</name>
<tag-class>com.ece.jee.HelloAttributeTag</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>message</name>
</attribute>
</tag>
• hello.jsp
……..
<br/>
<ex:HelloAttribute message="This is a custom tag with attribute" />
</body>
54
Maven
• Java tool
• build
• project management
• Homepage
• http://maven.apache.org
• Reference Documentation for Maven & core
Plugins
55 JEE - JSTL, Custom Tags & Maven
Common issues
• Managing multiple jars
• Dependencies and versions
• Maintaining project structure
• Building, publishing and deploying
56 JEE - JSTL, Custom Tags & Maven
Project Object Model (POM)
• Describes a project
• Name and Version
• Artifact Type
• Source Code Locations
• Dependencies
• Plugins
• Profiles (Alternate build configurations)
57 JEE - JSTL, Custom Tags & Maven
Maven Project
• Maven project is identified using (GAV):
• groupID: Arbitrary project grouping identifier (no spaces or
colons)
• Usually loosely based on Java package
• artfiactId: Name of project (no spaces or colons)
• version: Version of project
<?xml version="1.0" encoding="UTF-8"?>
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.ece.jee</groupId>
<artifactId>mavenApp</artifactId>
<version>1.0</version>
</project>
58 JEE - JSTL, Custom Tags & Maven
Packaging
• Specifies the “build type” for the project
• Example packaging types:
• pom, jar, war, ear, custom
• Default is jar
<?xml version="1.0" encoding="UTF-8"?>
<project>
<modelVersion>4.0.0</modelVersion>
<groupId>com.ece.jee</groupId>
<artifactId>mavenApp</artifactId>
<version>1.0</version>
<packaging>jar</packaging>
</project>
59 JEE - JSTL, Custom Tags & Maven
POM Inheritence
• POM files can inherit configuration
• groupId, version
• Project Config
• Dependencies
• Plugin configuration, etc.
<?xml version="1.0" encoding="UTF-8"?>
<project>
<parent>
<groupId>com.ece.jee</groupId>
<artifactId>mavenApp</artifactId>
<version>1.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>maven-training</artifactId>
<packaging>jar</packaging>
</project>
60 JEE - JSTL, Custom Tags & Maven
Maven Conventions
• Maven project structural hierarchy
• target: Default work directory
• src: All project source files go in this directory
• src/main: All sources that go into primary artifact
• src/test: All sources contributing to testing project
• src/main/java: All java source files
• src/main/webapp: All web source files
• src/main/resources: All non compiled source files
• src/test/java: All java test source files
• src/test/resources: All non compiled test source
61 JEE - JSTL, Custom Tags & Maven
Build Lifecycle
• Default lifecycle phases
• generate-sources/generate-resources
• compile
• test
• package
• integration-test (pre and post)
• Install
• deploy
• Specify the build phase you want and it runs previous
phases automatically
62 JEE - JSTL, Custom Tags & Maven
Maven Goals
• mvn install
• Invokes generate* and compile, test, package, integration-
test, install
• mvn clean
• Invokes just clean
• mvn clean compile
• Clean old builds and execute generate*, compile
• mvn compile install
• Invokes generate*, compile, test, integration-test, package,
install
• mvn test clean
• Invokes generate*, compile, test then cleans
63 JEE - JSTL, Custom Tags & Maven
Project Dependencies
• Dependencies consist of:
• GAV
• Scope: compile, test, provided (default=compile)
• Type: jar, pom, war, ear, zip (default=jar)
<project>
...
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
64 JEE - JSTL, Custom Tags & Maven
Dependencies & repositories
• Dependencies are downloaded from repositories
using HTTP
• Downloaded dependencies are cached in a local
repository
• Usually found in ${user.home}/.m2/repository
• Repository follows a simple directory structure
• {groupId}/{artifactId}/{version}/{artifactId}-
{version}.jar
65 JEE - JSTL, Custom Tags & Maven
Defining a repository
• Can be inherited from parent
• Repositories are keyed by id
• Downloading snapshots can be controlled
<project>
...
<repositories>
<repository>
<id>main-repo</id>
<name>ECE main repository</name>
<url>http://com.ece.jee/content/groups/main-repo</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
</project>
66 JEE - JSTL, Custom Tags & Maven
Maven Eclipse Plugin
• M2Eclipse provides:
• Launching Maven builds from within Eclipse
• Quick search dependencies
• Automatically downloading required dependencies
• Managing Maven dependencies
• Installation update site
http://download.eclipse.org/technology/m2e/releases
67 JEE - JSTL, Custom Tags & Maven
68 JEE - JSTL, Custom Tags & Maven
References
• JSTLExample inspired from http://www.journaldev.com/2090/jstl-
tutorial-with-examples-jstl-core-tags
• Further Reading:
• http://docs.oracle.com/javaee/5/tutorial/doc/bnakc.html
69

More Related Content

What's hot (17)

PDF
JAVA EE DEVELOPMENT (JSP and Servlets)
Talha Ocakçı
 
PDF
Java Web Programming [3/9] : Servlet Advanced
IMC Institute
 
PDF
Java Web Programming [6/9] : MVC
IMC Institute
 
PDF
Java Web Programming [2/9] : Servlet Basic
IMC Institute
 
PPTX
Introduction to JSP
Geethu Mohan
 
PDF
Java Web Programming [4/9] : JSP Basic
IMC Institute
 
PPTX
Database connect
Yoga Raja
 
PPT
Data Access with JDBC
BG Java EE Course
 
PPTX
Java Servlet
Yoga Raja
 
PDF
Java Web Programming [5/9] : EL, JSTL and Custom Tags
IMC Institute
 
PDF
Java Web Programming [8/9] : JSF and AJAX
IMC Institute
 
PPS
Jdbc api
kamal kotecha
 
PDF
Spring 4 Web App
Rossen Stoyanchev
 
PPT
Spring 3.x - Spring MVC
Guy Nir
 
PDF
AAI 1713-Introduction to Java EE 7
Kevin Sutter
 
PDF
Spring mvc
Guo Albert
 
PPTX
Advance java session 5
Smita B Kumar
 
JAVA EE DEVELOPMENT (JSP and Servlets)
Talha Ocakçı
 
Java Web Programming [3/9] : Servlet Advanced
IMC Institute
 
Java Web Programming [6/9] : MVC
IMC Institute
 
Java Web Programming [2/9] : Servlet Basic
IMC Institute
 
Introduction to JSP
Geethu Mohan
 
Java Web Programming [4/9] : JSP Basic
IMC Institute
 
Database connect
Yoga Raja
 
Data Access with JDBC
BG Java EE Course
 
Java Servlet
Yoga Raja
 
Java Web Programming [5/9] : EL, JSTL and Custom Tags
IMC Institute
 
Java Web Programming [8/9] : JSF and AJAX
IMC Institute
 
Jdbc api
kamal kotecha
 
Spring 4 Web App
Rossen Stoyanchev
 
Spring 3.x - Spring MVC
Guy Nir
 
AAI 1713-Introduction to Java EE 7
Kevin Sutter
 
Spring mvc
Guo Albert
 
Advance java session 5
Smita B Kumar
 

Viewers also liked (20)

PDF
Lecture 10 - Java Server Faces (JSF)
Fahad Golra
 
PDF
Tutorial 4 - Basics of Digital Photography
Fahad Golra
 
PDF
Lecture 1: Introduction to JEE
Fahad Golra
 
PDF
Lecture 8 Enterprise Java Beans (EJB)
Fahad Golra
 
PDF
TNAPS 3 Installation
tncor
 
PPT
Ejb in java. part 1.
Asya Dudnik
 
PDF
2012-12-01 03 Битва ORM: Hibernate vs MyBatis. Давайте жить дружно!
Омские ИТ-субботники
 
PDF
Apache Lucene + Hibernate = Hibernate Search
Vitebsk Miniq
 
PPT
JSP Standart Tag Lİbrary - JSTL
seleciii44
 
PDF
JSP Standard Tag Library
Ilio Catallo
 
PDF
Enterprise Java Beans - EJB
Peter R. Egli
 
PPT
EJB .
ayyagari.vinay
 
PPTX
Convexity calls
Bhushan Maskay
 
PPTX
Convexity calls
Bhushan Maskay
 
PPTX
Avnet's RaBET Overview
Avnet Electronics Marketing
 
PPTX
Budget templates 2013 2014 - exports
Teamglobal_Corporate
 
PPT
[转帖]趣味定律
roro_11
 
PPTX
Gamification beyond Gamification
Ákos Csertán
 
PDF
Indonesia
corkg
 
PPTX
The next big wave
Bhushan Maskay
 
Lecture 10 - Java Server Faces (JSF)
Fahad Golra
 
Tutorial 4 - Basics of Digital Photography
Fahad Golra
 
Lecture 1: Introduction to JEE
Fahad Golra
 
Lecture 8 Enterprise Java Beans (EJB)
Fahad Golra
 
TNAPS 3 Installation
tncor
 
Ejb in java. part 1.
Asya Dudnik
 
2012-12-01 03 Битва ORM: Hibernate vs MyBatis. Давайте жить дружно!
Омские ИТ-субботники
 
Apache Lucene + Hibernate = Hibernate Search
Vitebsk Miniq
 
JSP Standart Tag Lİbrary - JSTL
seleciii44
 
JSP Standard Tag Library
Ilio Catallo
 
Enterprise Java Beans - EJB
Peter R. Egli
 
Convexity calls
Bhushan Maskay
 
Convexity calls
Bhushan Maskay
 
Avnet's RaBET Overview
Avnet Electronics Marketing
 
Budget templates 2013 2014 - exports
Teamglobal_Corporate
 
[转帖]趣味定律
roro_11
 
Gamification beyond Gamification
Ákos Csertán
 
Indonesia
corkg
 
The next big wave
Bhushan Maskay
 
Ad

Similar to Lecture 5 JSTL, custom tags, maven (20)

PPTX
Implementing java server pages standard tag library v2
Soujanya V
 
PPTX
Advance java session 16
Smita B Kumar
 
PPTX
JSTL.pptx
SPAMVEDANT
 
PPTX
18CSC311J Web Design and Development UNIT-3
Sivakumar M
 
PPT
Struts2-Spring=Hibernate
Jay Shah
 
PPT
Java .ppt
MuhammedYaseenMc
 
PPT
25.ppt
veningstonk
 
PPT
azuretip1detailshereforlearninganddoingpractice
Avinashk515020
 
PPTX
Java EE 8 Update
Ryan Cuprak
 
PPTX
Effiziente persistierung
Thorben Janssen
 
PDF
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 8 ...
WebStackAcademy
 
PDF
Build Java Web Application Using Apache Struts
weili_at_slideshare
 
PPTX
SCWCD : Java server pages CHAP : 9
Ben Abdallah Helmi
 
PDF
Migration strategies 4
Wenhua Wang
 
PDF
10 jsp-scripting-elements
Phạm Thu Thủy
 
PDF
Play Framework and Activator
Kevin Webber
 
PDF
Iasi code camp 12 october 2013 jax-rs-jee-ecosystem - catalin mihalache
Codecamp Romania
 
PDF
Session_15_JSTL.pdf
TabassumMaktum
 
PPT
Jstl Guide
Yuval Zilberstein
 
Implementing java server pages standard tag library v2
Soujanya V
 
Advance java session 16
Smita B Kumar
 
JSTL.pptx
SPAMVEDANT
 
18CSC311J Web Design and Development UNIT-3
Sivakumar M
 
Struts2-Spring=Hibernate
Jay Shah
 
Java .ppt
MuhammedYaseenMc
 
25.ppt
veningstonk
 
azuretip1detailshereforlearninganddoingpractice
Avinashk515020
 
Java EE 8 Update
Ryan Cuprak
 
Effiziente persistierung
Thorben Janssen
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 8 ...
WebStackAcademy
 
Build Java Web Application Using Apache Struts
weili_at_slideshare
 
SCWCD : Java server pages CHAP : 9
Ben Abdallah Helmi
 
Migration strategies 4
Wenhua Wang
 
10 jsp-scripting-elements
Phạm Thu Thủy
 
Play Framework and Activator
Kevin Webber
 
Iasi code camp 12 october 2013 jax-rs-jee-ecosystem - catalin mihalache
Codecamp Romania
 
Session_15_JSTL.pdf
TabassumMaktum
 
Jstl Guide
Yuval Zilberstein
 
Ad

More from Fahad Golra (9)

PDF
Seance 4- Programmation en langage C
Fahad Golra
 
PDF
Seance 3- Programmation en langage C
Fahad Golra
 
PDF
Seance 2 - Programmation en langage C
Fahad Golra
 
PDF
Seance 1 - Programmation en langage C
Fahad Golra
 
PDF
Tutorial 3 - Basics of Digital Photography
Fahad Golra
 
PDF
Tutorial 2 - Basics of Digital Photography
Fahad Golra
 
PDF
Tutorial 1 - Basics of Digital Photography
Fahad Golra
 
PPTX
Deviation Detection in Process Enactment
Fahad Golra
 
PPTX
Meta l metacase tools & possibilities
Fahad Golra
 
Seance 4- Programmation en langage C
Fahad Golra
 
Seance 3- Programmation en langage C
Fahad Golra
 
Seance 2 - Programmation en langage C
Fahad Golra
 
Seance 1 - Programmation en langage C
Fahad Golra
 
Tutorial 3 - Basics of Digital Photography
Fahad Golra
 
Tutorial 2 - Basics of Digital Photography
Fahad Golra
 
Tutorial 1 - Basics of Digital Photography
Fahad Golra
 
Deviation Detection in Process Enactment
Fahad Golra
 
Meta l metacase tools & possibilities
Fahad Golra
 

Recently uploaded (20)

PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PDF
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PPTX
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
PPTX
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
PPTX
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
PDF
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PPTX
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PDF
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PDF
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Digger Solo: Semantic search and maps for your local files
seanpedersen96
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
Migrating Millions of Users with Debezium, Apache Kafka, and an Acyclic Synch...
MD Sayem Ahmed
 
Understanding the Need for Systemic Change in Open Source Through Intersectio...
Imma Valls Bernaus
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
Tally software_Introduction_Presentation
AditiBansal54083
 
Revenue streams of the Wazirx clone script.pdf
aaronjeffray
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 

Lecture 5 JSTL, custom tags, maven

  • 1. JEE - JSTL, Custom Tags and Maven Fahad R. Golra ECE Paris Ecole d'Ingénieurs - FRANCE
  • 2. Lecture 4 - JSTL, Custom Tags & Maven • JSTL • MVC • Tag Libraries • Custom Tags • Basic Tags with/without body • Attributes in custom tags • Maven 2 JEE - JSTL, Custom Tags & Maven
  • 3. Best practices • Modularity • Separation of concerns • Loose-coupling • Abstraction • Encapsulation • Reuse 3 JEE - JSTL, Custom Tags & Maven
  • 4. Web Application Development • Model-View-Controller (MVC) Architecture • Model • Business objects or domain objects • POJOs & JavaBeans • View • Visual representation of model • JSP, JSF • Controller • Navigation Flow & Model-view integration • Servlets 4 JEE - JSTL, Custom Tags & Maven
  • 5. JavaBeans [Model] • Must follow JavaBeans Conventions • Public Default Constructor (no parameter) • Accessor methods for a property p of Type T • GET: public T getP() • SET: public void setP(T) • IS: public boolean isP() • Persistence - Object Serialization • JavaBean Conventions: http://docstore.mik.ua/orelly/java-ent/jnut/ch06_02.htm 5 JEE - JSTL, Custom Tags & Maven
  • 6. JavaBean Example (Recall) package com.ece.jee; public class PersonBean implements java.io.Serializable { private static final long serialVersionUID = 1L; private String firstName = null; private String lastName = null; private int age = 0; public PersonBean() { } public String getFirstName() { return firstName; } public String getLastName() { return lastName; }6
  • 7. JavaBean Example (Recall) public int getAge() { return age; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public void setAge(Integer age) { this.age = age; } } 7
  • 8. JSP [View] • Best practice goals • Minimal business logic • Reuse • Design options • JSP + Standard Action Tags + JavaBeans • JSP + Standard Actions + JSTL + JavaBeans 8 JEE - JSTL, Custom Tags & Maven
  • 9. JSTL • Conceptual extension to JSP Standard Actions • XML tags • Supports common structural tasks such as iterations and conditions, tags for manipulating XML documents, internationalization tags, and SQL tags. • JSP Standard Tag Library • Defined as Java Community Process • Custom Tag Library mechanism (discuss soon) • Available within JSP/Servlet containers 9 JEE - JSTL, Custom Tags & Maven
  • 10. JSTL Library • JSTL is installed in most common Application Servers like JBoss, Glassfish etc. • Note: Not provided by Tomcat • Installation in Tomcat • Download from https://jstl.java.net/download.html • Drag the JSTL API & Implementation jars in the /WEB-INF/lib folder of eclipse project. 10 JEE - JSTL, Custom Tags & Maven
  • 11. Example using scriptlet <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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=UTF-8"> <title>Count to 10 using JSP scriptlet</title> </head> <body> <% for (int i = 1; i <= 10; i++) { %> <%=i%> <br /> <% } %> </body> </html> 11
  • 12. Example using JSTL <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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=UTF-8"> <title>Count to 10 using JSTL</title> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> </head> <body> <c:forEach var="i" begin="1" end="10" step="1"> <c:out value="${i}" /> <br /> </c:forEach> </body> </html> 12
  • 13. The JSTL Tag Libraries • Core Tags • Formatting Tags • SQL Tags • XML Tags • JSTL Functions 13 JEE - JSTL, Custom Tags & Maven
  • 14. Tag Library Prefix & URI 14 JEE - JSTL, Custom Tags & Maven Library URI Prefix Core http://java.sun.com/jsp/jstl/core c XML Processing http://java.sun.com/jsp/jstl/xml x Formatting http://java.sun.com/jsp/jstl/fmt fmt Database Access http://java.sun.com/jsp/jstl/sql sql Functions http://java.sun.com/jsp/jstl/functions fn <%@taglib prefix= c uri= http://java.sun.com/ jsp/jstl/core %> where to find the Java class or tag file that implements the custom action which elements are part of a custom tag library
  • 15. Core Tag Library • Contains structural tags that are essential to nearly all Web applications. • Examples of core tag libraries include looping, expression evaluation, and basic input and output. • Syntax: <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 15 JEE - JSTL, Custom Tags & Maven
  • 16. Core Tag Library 16 Tag! Description ! <c:out >! Like <%= ... >, but for expressions. ! <c:set >! Sets the result of an expression evaluation in a 'scope'! <c:remove >! Removes a scoped variable (from a particular scope, if specified). ! <c:catch>! Catches any Throwable that occurs in its body and optionally exposes it.! <c:if>! Simple conditional tag which evalutes its body if the supplied condition is true.! <c:choose>! Simple conditional tag that establishes a context for mutually exclusive conditional operations, marked by <when> and <otherwise> ! <c:when>! Subtag of <choose> that includes its body if its condition evalutes to 'true'.!
  • 17. Core Tag Library 17 Tag! Description ! <c:otherwise >! Subtag of <choose> that follows <when> tags and runs only if all of the prior conditions evaluated to 'false'.! <c:import>! Retrieves an absolute or relative URL and exposes its contents to either the page, a String in 'var', or a Reader in 'varReader'.! <c:forEach >! The basic iteration tag, accepting many different collection types and supporting subsetting and other functionality .! <c:forTokens>! Iterates over tokens, separated by the supplied delimeters.! <c:param>! Adds a parameter to a containing 'import' tag's URL.! <c:redirect >! Redirects to a new URL.! <c:url>! Creates a URL with optional query parameters!
  • 18. • Catches an exception thrown by JSP elements in its body • The exception can optionally be saved as a page scope variable • Syntax: <c:catch> JSP elements </c:catch> 18 JEE - JSTL, Custom Tags & Maven <c: catch>
  • 19. • only the first <c:when> action that evaluates to true is processed • if no <c:when> evaluates to true <c:otherwise> is processed, if exists • Syntax: <c:choose> 1 or more <c:when> tags and optionally a <c:otherwise> tag </c:choose> 19 JEE - JSTL, Custom Tags & Maven <c: choose>
  • 20. • Evaluates its body once for each element in a collection – java.util.Collection, java.util.Iterator, java.util.Enumeration, java.util.Map – array of Objects or primitive types • Syntax: <c:forEach items=“collection” [var=“var”] [varStatus=“varStatus”] [begin=“startIndex”] [end=“endIndex”] [step=“increment”]> JSP elements </c:forEach> 20 JEE - JSTL, Custom Tags & Maven <c: forEach>
  • 21. • Evaluates its body once for each token n a string delimited by one of the delimiter characters • Syntax: <c:forTokens items=“stringOfTokens” delims=“delimiters” [var=“var”] [varStatus=“varStatus”] [begin=“startIndex”] [end=“endIndex”] [step=“increment”]> JSP elements </c:forTokens> 21 JEE - JSTL, Custom Tags & Maven <c: forTokens>
  • 22. • Evaluates its body only if the specified expression is true • Syntax1: <c:if test=“booleanExpression” var=“var” [scope=“page|request|session| application”] /> • Syntax2: <c:if test=“booleanExpression” > JSP elements </c:if> 22 JEE - JSTL, Custom Tags & Maven <c: if>
  • 23. • imports the content of an internal or external resource like <jsp:include> for internal resources however, allows the import of external resources as well (from a different application OR different web container) • Syntax: <c:import url=“url” [context=“externalContext”] [var=“var”] [scope=“page|request|session| application”] [charEncoding=“charEncoding”]> Optional <c:param> actions </c:import> 23 JEE - JSTL, Custom Tags & Maven <c: import>
  • 24. • Nested action in <c:import> <c:redirect> <c:url> to add a request parameter • Syntax 1: <c:param name=“parameterName” value=“parameterValue” /> • Syntax 2: <c:param name=“parameterName”> parameterValue </c:param> 24 JEE - JSTL, Custom Tags & Maven <c: param>
  • 25. • Adds the value of the evaluated expression to the response buffer • Syntax 1: <c:out value=“expression” [excapeXml=“true| false”] [default=“defaultExpression”] /> • Syntax 2: <c:out value=“expression” [excapeXml=“true| false”]> defaultExpression </c:out> 25 JEE - JSTL, Custom Tags & Maven <c: out>
  • 26. • Sends a redirect response to a client telling it to make a new request for the specified resource • Syntax 1: <c:redirect url=“url” [context=“externalContextPath”] /> • Syntax 2: <c:redirect url=“url” [context=“externalContextPath”] > <c:param> tags </c:redirect> 26 JEE - JSTL, Custom Tags & Maven <c: redirect>
  • 27. • removes a scoped variable • if no scope is specified the variable is removed from the first scope it is specified • does nothing if the variable is not found • Syntax: <c:remove var=“var” [scope=“page|request|session| application”] /> 27 JEE - JSTL, Custom Tags & Maven <c: remove>
  • 28. • sets a scoped variable or a property of a target object to the value of a given expression • The target object must be of type java.util.Map or a Java Bean with a matching setter method • Syntax 1: <c:set value=“expression” target=“beanOrMap” property=“propertyName” /> • Syntax 2: <c:set value=“expression” var=“var” scope=“page| request|session|application” /> 28 JEE - JSTL, Custom Tags & Maven <c: set>
  • 29. • applies encoding and conversion rules for a relative or absolute URL – URL encoding of parameters specified in <c:param> tags – context-relative path to server-relative path – add session Id path parameter for context- or page-relative path • Syntax: <c:url url=“url” [context=“externalContextPath”] [var=“var”] scope=“page|request|session| application” > <c:param> actions </c:url> 29 JEE - JSTL, Custom Tags & Maven <c: url>
  • 30. Formatting Tag Library • Contains tags that are used to parse data. • Some of these tags will parse data, such as dates, differently based on the current locale. • Syntax: <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %> 30 JEE - JSTL, Custom Tags & Maven
  • 31. Formatting Tag Library 31 JEE - JSTL, Custom Tags & Maven Tag Description <fmt:formatNumber> To render numerical value with specific precision or format. <fmt:parseNumber> Parses the string representation of a number, currency, or percentage. <fmt:formatDate> Formats a date and/or time using the supplied styles and pattern <fmt:parseDate> Parses the string representation of a date and/or time <fmt:bundle> Loads a resource bundle to be used by its tag body. <fmt:setLocale> Stores the given locale in the locale configuration variable.
  • 32. Formatting Tag Library 32 JEE - JSTL, Custom Tags & Maven Tag Description <fmt:formatNumber> To render numerical value with specific precision or format. <fmt:parseNumber> Parses the string representation of a number, currency, or percentage. <fmt:formatDate> Formats a date and/or time using the supplied styles and pattern <fmt:parseDate> Parses the string representation of a date and/or time <fmt:bundle> Loads a resource bundle to be used by its tag body. <fmt:setLocale> Stores the given locale in the locale configuration variable.
  • 33. Database Tag Library • Contains tags that can be used to access SQL databases. • These tags are normally used to create prototype programs only. This is because most programs will not handle database access directly from JSP pages. • Syntax: <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %> 33 JEE - JSTL, Custom Tags & Maven
  • 34. Database Tag Library 34 JEE - JSTL, Custom Tags & Maven Tag Description <sql:setDataSource> Creates a simple DataSource suitable only for prototyping <sql:query> Executes the SQL query defined in its body or through the sql attribute. <sql:update> Executes the SQL update defined in its body or through the sql attribute. <sql:param> Sets a parameter in an SQL statement to the specified value. <sql:dateParam> Sets a parameter in an SQL statement to the specified java.util.Date value. <sql:transaction > Provides nested database action elements with a shared Connection, set up to execute all statements as one transaction.
  • 35. XML Tag Library • Contains tags that can be used to access XML elements. • XML is used in many Web applications, XML processing is an important feature of JSTL. • Syntax: <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %> 35 JEE - JSTL, Custom Tags & Maven
  • 36. XML Tag Library 36 JEE - JSTL, Custom Tags & Maven Tag Description <x:out> Like <%= ... >, but for XPath expressions. <x:parse> Use to parse XML data specified either via an attribute or in the tag body. <x:set > Sets a variable to the value of an XPath expression. <x:if > Evaluates a test XPath expression and if it is true, it processes its body. If the test condition is false, the body is ignored. <x:forEach> To loop over nodes in an XML document.
  • 37. XML Tag Library 37 JEE - JSTL, Custom Tags & Maven Tag Description <x:choose> Simple conditional tag that establishes a context for mutually exclusive conditional operations, marked by <when> and <otherwise> <x:when > Subtag of <choose> that includes its body if its expression evalutes to 'true' <x:otherwise > Subtag of <choose> that follows <when> tags and runs only if all of the prior conditions evaluated to 'false' <x:transform > Applies an XSL transformation on a XML document <x:param > Use along with the transform tag to set a parameter in the XSLT stylesheet
  • 38. JSTL Functions • JSTL includes a number of standard functions, most of which are common string manipulation functions. • Syntax: <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> 38 JEE - JSTL, Custom Tags & Maven
  • 39. JSTL Functions 39 Function Description fn:contains() Tests if an input string contains the specified substring. fn:containsIgnoreCase() Tests if an input string contains the specified substring in a case insensitive way. fn:endsWith() Tests if an input string ends with the specified suffix. fn:escapeXml() Escapes characters that could be interpreted as XML markup. fn:indexOf() Returns the index within a string of the first occurrence of a specified substring. fn:join() Joins all elements of an array into a string. fn:length() Returns the number of items in a collection, or the number of characters in a string. fn:replace() Returns a string resulting from replacing in an input string all occurrences with a given string. fn:split() Splits a string into an array of substrings.
  • 40. Custom Tags • User defined JSP language elements (as opposed to standard tags) • Encapsulates recurring tasks • Distributed in a “custom made” tag library 40 JEE - JSTL, Custom Tags & Maven
  • 41. Why use custom tags? • Custom tags can be used for • Generating content for a JSP page • Accessing a page’s JavaBeans • Introducing new JavaBeans • Introducing new scripting variables • Using the strength of Java 41 JEE - JSTL, Custom Tags & Maven
  • 42. Custom Tag Syntax • Like the standard actions, custom tags follow XML syntax conventions <prefix:name attribute=”value” attribute=”value”/> 
 <prefix:name attribute=”value” attribute=”value”>
 body content
 </prefix:name> 42 JEE - JSTL, Custom Tags & Maven
  • 43. Custom tags architecture • Custom tag architecture is made up of: • Tag handler class • Defines tag's behaviour • Tag library descriptor (TLD) • Maps XML elements to tag handler class • JSP file (user of custom tags) • Uses tags 43 JEE - JSTL, Custom Tags & Maven
  • 44. Tag Handlers • A tag handler class must implement one of the following interfaces: • javax.servlet.jsp.tagext.Tag • javax.servlet.jsp.tagext.IterationTag • javax.servlet.jsp.tagext.BodyTag • Usually extends utility class • javax.servlet.jsp.tagext.TagSupport • javax.servlet.jsp.tagext.BodyTagSupport • javax.servlet.jsp.tagext.SimpleTagSupport • Located in the same directory as servlet class files • Tag attributes are managed as JavaBeans properties (i.e., via getters and setters) 44 JEE - JSTL, Custom Tags & Maven
  • 45. Tag Library Descriptor • Defines tag syntax and maps tag names to handler classes • Specifies tag attributes • Attribute names and optional types • Required vs. optional • Compile-time vs. run-time values • Specifies tag variables (name, scope, etc.) • Declares tag library validator and lifecycle event handlers, if any 45 JEE - JSTL, Custom Tags & Maven
  • 46. How to implement, use & deploy • Four steps to follow: • write tag handlers • write so called tag library descriptor (TLD) file • package a set of tag handlers and TLD file into tag library • write JSP pages that use these tags. Then you deploy the tag library along with JSP pages. • Syntax to use custom Tags in JSP is same as JSTL <%@ taglib prefix="myprefix" uri=”myuri” %> 46 JEE - JSTL, Custom Tags & Maven
  • 47. Example: HelloTag.java package com.ece.jee; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.SimpleTagSupport; public class HelloTag extends SimpleTagSupport { public void doTag() throws JspException, IOException { JspWriter out = getJspContext().getOut(); out.println("Hello, I am body-less Custom Tag!"); } } 47
  • 48. Example: custom.tld <?xml version="1.0" encoding="UTF-8"?> <taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http:// java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd" > <tlib-version>1.0</tlib-version> <short-name>ex</short-name> <uri>http://jee.ece.com</uri> <tag> <name>Hello</name> <tag-class>com.ece.jee.HelloTag</tag-class> <body-content>empty</body-content> </tag> </taglib> 48
  • 49. Example: hello.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ taglib prefix="ex" uri="http://jee.ece.com"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>A sample custom tag</title> </head> <body> <ex:Hello /> </body> </html> 49
  • 50. Custom Tags with Body • The <body-content> specifies what type of content is allowed • empty - no nested content • sriptless - text, EL & JSP without sriptlets & expressions • JSP - Everything allowed in JSP • tagdependent - tag evaluates itself <tag> <name>Hello</name> <tag-class>com.ece.jee.HelloTag</tag-class> <body-content>empty</body-content> </tag> 50 JEE - JSTL, Custom Tags & Maven
  • 51. Custom Tags with Body package com.ece.jee; import java.io.IOException; import java.io.StringWriter; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; public class HelloBodyTag extends SimpleTagSupport { StringWriter sw = new StringWriter(); public void doTag() throws JspException, IOException { getJspBody().invoke(sw); getJspContext().getOut().println(sw.toString()); } } 51
  • 52. Custom Tags with Body • custom.tld <tag> <name>HelloBody</name> <tag-class>com.ece.jee.HelloBodyTag</tag-class> <body-content>scriptless</body-content> </tag> • hello.jsp <body> <ex:Hello /> <br/> <ex:HelloBody> Hello! I am a custom Tag with body </ex:HelloBody> </body> 52
  • 53. Custom Tags with attributes public class HelloAttributeTag extends TagSupport { private static final long serialVersionUID = 1L; private String message; public void setMessage(String msg) { this.message = msg; } @Override public int doStartTag() throws JspException { JspWriter out = pageContext.getOut(); if (message != null) { try { out.println(message); } catch (IOException e) { e.printStackTrace(); } } return SKIP_BODY; } } 53
  • 54. Custom Tags with attributes • custom.tld <tag> <name>HelloAttribute</name> <tag-class>com.ece.jee.HelloAttributeTag</tag-class> <body-content>scriptless</body-content> <attribute> <name>message</name> </attribute> </tag> • hello.jsp …….. <br/> <ex:HelloAttribute message="This is a custom tag with attribute" /> </body> 54
  • 55. Maven • Java tool • build • project management • Homepage • http://maven.apache.org • Reference Documentation for Maven & core Plugins 55 JEE - JSTL, Custom Tags & Maven
  • 56. Common issues • Managing multiple jars • Dependencies and versions • Maintaining project structure • Building, publishing and deploying 56 JEE - JSTL, Custom Tags & Maven
  • 57. Project Object Model (POM) • Describes a project • Name and Version • Artifact Type • Source Code Locations • Dependencies • Plugins • Profiles (Alternate build configurations) 57 JEE - JSTL, Custom Tags & Maven
  • 58. Maven Project • Maven project is identified using (GAV): • groupID: Arbitrary project grouping identifier (no spaces or colons) • Usually loosely based on Java package • artfiactId: Name of project (no spaces or colons) • version: Version of project <?xml version="1.0" encoding="UTF-8"?> <project> <modelVersion>4.0.0</modelVersion> <groupId>com.ece.jee</groupId> <artifactId>mavenApp</artifactId> <version>1.0</version> </project> 58 JEE - JSTL, Custom Tags & Maven
  • 59. Packaging • Specifies the “build type” for the project • Example packaging types: • pom, jar, war, ear, custom • Default is jar <?xml version="1.0" encoding="UTF-8"?> <project> <modelVersion>4.0.0</modelVersion> <groupId>com.ece.jee</groupId> <artifactId>mavenApp</artifactId> <version>1.0</version> <packaging>jar</packaging> </project> 59 JEE - JSTL, Custom Tags & Maven
  • 60. POM Inheritence • POM files can inherit configuration • groupId, version • Project Config • Dependencies • Plugin configuration, etc. <?xml version="1.0" encoding="UTF-8"?> <project> <parent> <groupId>com.ece.jee</groupId> <artifactId>mavenApp</artifactId> <version>1.0</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>maven-training</artifactId> <packaging>jar</packaging> </project> 60 JEE - JSTL, Custom Tags & Maven
  • 61. Maven Conventions • Maven project structural hierarchy • target: Default work directory • src: All project source files go in this directory • src/main: All sources that go into primary artifact • src/test: All sources contributing to testing project • src/main/java: All java source files • src/main/webapp: All web source files • src/main/resources: All non compiled source files • src/test/java: All java test source files • src/test/resources: All non compiled test source 61 JEE - JSTL, Custom Tags & Maven
  • 62. Build Lifecycle • Default lifecycle phases • generate-sources/generate-resources • compile • test • package • integration-test (pre and post) • Install • deploy • Specify the build phase you want and it runs previous phases automatically 62 JEE - JSTL, Custom Tags & Maven
  • 63. Maven Goals • mvn install • Invokes generate* and compile, test, package, integration- test, install • mvn clean • Invokes just clean • mvn clean compile • Clean old builds and execute generate*, compile • mvn compile install • Invokes generate*, compile, test, integration-test, package, install • mvn test clean • Invokes generate*, compile, test then cleans 63 JEE - JSTL, Custom Tags & Maven
  • 64. Project Dependencies • Dependencies consist of: • GAV • Scope: compile, test, provided (default=compile) • Type: jar, pom, war, ear, zip (default=jar) <project> ... <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> </dependencies> </project> 64 JEE - JSTL, Custom Tags & Maven
  • 65. Dependencies & repositories • Dependencies are downloaded from repositories using HTTP • Downloaded dependencies are cached in a local repository • Usually found in ${user.home}/.m2/repository • Repository follows a simple directory structure • {groupId}/{artifactId}/{version}/{artifactId}- {version}.jar 65 JEE - JSTL, Custom Tags & Maven
  • 66. Defining a repository • Can be inherited from parent • Repositories are keyed by id • Downloading snapshots can be controlled <project> ... <repositories> <repository> <id>main-repo</id> <name>ECE main repository</name> <url>http://com.ece.jee/content/groups/main-repo</url> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> </project> 66 JEE - JSTL, Custom Tags & Maven
  • 67. Maven Eclipse Plugin • M2Eclipse provides: • Launching Maven builds from within Eclipse • Quick search dependencies • Automatically downloading required dependencies • Managing Maven dependencies • Installation update site http://download.eclipse.org/technology/m2e/releases 67 JEE - JSTL, Custom Tags & Maven
  • 68. 68 JEE - JSTL, Custom Tags & Maven
  • 69. References • JSTLExample inspired from http://www.journaldev.com/2090/jstl- tutorial-with-examples-jstl-core-tags • Further Reading: • http://docs.oracle.com/javaee/5/tutorial/doc/bnakc.html 69