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>
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
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
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
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
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