Jsp 2 0 and jstl principles and patterns l.jpg
This presentation is the property of its rightful owner.
Sponsored Links
1 / 53

JSP 2.0 and JSTL: Principles and Patterns PowerPoint PPT Presentation

  • Uploaded on
  • Presentation posted in: General

JSP 2.0 and JSTL: Principles and Patterns. Shawn Bayern Research Programmer, Yale University JSTL reference-implementation lead Author, JSTL in Action Web Development with JavaServer Pages. The J2EE Presentation Tier. Four key questions to answer today: What justifies JSP 2.0?

Download Presentation

JSP 2.0 and JSTL: Principles and Patterns

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript

Jsp 2 0 and jstl principles and patterns l.jpg

JSP 2.0 and JSTL: Principles and Patterns

Shawn Bayern

Research Programmer, Yale University

JSTL reference-implementation lead

Author, JSTL in Action

Web Development with JavaServer Pages

The j2ee presentation tier l.jpg

The J2EE Presentation Tier

  • Four key questions to answer today:

    • What justifies JSP 2.0?

    • What are its major new features?

    • What is JSTL?

    • What do these new technologies suggest about development patterns and best practices?

Crash course on the j2ee presentation tier l.jpg

Crash course on the J2EE Presentation Tier


  • Current standards:

    • JSP 1.2

    • Servlet 2.3

    • JSTL 1.0





  • In a few months:

    • JSP 2.0

    • Servlet 2.4

    • JSTL 1.1

Crash course on the j2ee presentation tier4 l.jpg

Crash course on the J2EE presentation tier

  • Servlets

    • Java classes that handle requests by producing responses (e.g., HTTP requests and responses)

  • JavaServer Pages (JSP)

    • HTML-like pages with some dynamic content.

    • They turn into servlets automatically.

  • JSP Standard Tag Library (JSTL)

    • Set of standard components for JSP.

    • It is used inside JSP pages.

Organization of the platform l.jpg

Organization of the platform


web pages

Your application


JavaServer Pages (JSP)

Java Servlet API

Java language

What kinds of things go in jsp pages l.jpg

What kinds of things go in JSP pages?





String a = ”goat”;


<% if (a.equals(”pig”) {%>


<% } %>

  • Java (and more?) embedded within template text

  • Access to implicit objects: request, response, etc.

  • Conditional blocks, loops—manually constructed

What kinds of things go in jsp pages7 l.jpg

What kinds of things go in JSP pages?

Tag libraries


<c:if test=”${c}”>

c is true



Round and round we go


  • XML tags

  • Invoke Java logic behind the scenes.

  • May access body, e.g., for iteration, conditional inclusion—or just as arbitrary parameter

  • May access PageContext

  • Libraries and prefixes

Question 1 l.jpg

Question 1

  • Why JSP 2.0?

    (Or, what’s wrong with the current version of JSP?)

Why we like jsp in the first place l.jpg

Why we like JSP in the first place ()

  • Open standard with support from many vendors

  • The performance and scalability of servlets (for JSP pages compile into servlets)

  • Extensibility (custom tags)

  • Easy integration with other J2EE and Java technologies (Servlets, EJB)

What s irritating about jsp l.jpg

What’s irritating about JSP? ()

  • The tag-extension protocol is too complicated

Tag handler



Too hard for Gosling, even?






What s irritating about jsp11 l.jpg

What’s irritating about JSP? ()

  • Also, tags don’t support certain kinds of code reuse.

    <font color=”<%=statusColor%>”>

    <% for (…) { %>

    <%= customer %>: <%= hatSize %>

    <% } %>



for(…) {



What s bad about jsp l.jpg

What’s bad about JSP? ()

  • The general consensus says…


    • They complicate abstraction and code reuse.

    • They make it harder for nonprogrammers to maintain pages

Question 2 l.jpg

Question 2

  • What new features does JSP 2.0 offer?

    (Or, how does it fix the issues we just raised?)

How does jsp 2 0 address these issues l.jpg

How does JSP 2.0 address these issues?

  • Expression language

  • Tag files

  • Simplified Tag API (SimpleTag versus Tag)

  • Improved XML syntax

    Also, though it’s not really part of JSP,

    JSTL improves things too.

    The end result:

    JSP pages become easier to write and maintain.

The jsp expression language el goals and principles l.jpg

The JSP Expression Language (EL): Goals and principles

  • The major goal: simplicity.

    • The language should be usable by nonprogrammers.

  • Inspirations: JavaScript, XPath

    • But it’s much simpler than even these basic expression languages.

      • Quick: what does //foo = ‘bar’ mean in XPath?

      • Or what happens with age + 3 in ECMAScript?

Xpath foo bar l.jpg

XPath (//foo = ‘bar’)

  • “If one object to be compared is a node-set and the other is a string, then the comparison will be true if and only if there is a node in the node-set such that the result of performing the comparison on the string-value of the node and the other string is true.”

Ecmascript age 3 l.jpg

ECMAScript (age + 3)

  • Page 62 of 188:

    The Addition operator ( + )

    The addition operator either performs string concatenation or numeric addition.

    The production AdditiveExpression : AdditiveExpression + MultiplicativeExpression is evaluated as


    1. Evaluate AdditiveExpression.

    2. Call GetValue(Result(1)).

    3. Evaluate MultiplicativeExpression.

    4. Call GetValue(Result(3)).

    5. Call ToPrimitive(Result(2)).

    6. Call ToPrimitive(Result(4)).

    7. If Type(Result(5)) is String or Type(Result(6)) is String, go to step 12. (Note that this step differs

    from step 3 in the comparison algorithm for the relational operators, by using or instead of and.)

    8. Call ToNumber(Result(5)).

    9. Call ToNumber(Result(6)).

    10. Apply the addition operation to Result(8) and Result(9). See the note below (11.6.3).

    11. Return Result(10).

    12. Call ToString(Result(5)).

    13. Call ToString(Result(6)).

    14. Concatenate Result(12) followed by Result(13).

    15. Return Result(14).

29. One-half of self-employment tax.

Attach Schedule SE.

30. Self-employed health insurance

deduction (see page 33)

31. Self-employed SEP, SIMPLE, and

qualified plans

32. Penalty on early withdrawal of savings

33. Alimony paid

34. Add lines 23 through 33a

35. Subtract line 34 from line 22. This is

your adjusted gross income.

The jsp expression language el key syntax l.jpg

The JSP Expression Language (EL): Key syntax

  • Expressions appear between ${ and }.

    • Note that ${ and } may contain whole expressions, not just variable names, as in the Bourne shell (and its dozen derivatives.)

    • E.g., ${myExpression + 2}

  • Expressions’ default targets are scoped attributes (page, request, session, application)

    • ${duck}≡ pageContext.findAttribute(“duck”)

The jsp expression language el key syntax19 l.jpg

The JSP Expression Language (EL): Key syntax

  • The . and [] operators refer to JavaBean-style properties and Map elements:

    • ${duck.beakColor}can resolve to

      ((Duck) pageContext.getAttribute(”duck”)).getBeakColor()

  • Note the automatic type-cast.

    • This is one of the great features of the EL: users do not need to concern themselves with types in most cases (even though the underlying types of data objects are preserved.)

The jsp expression language el advanced data access l.jpg

The JSP Expression Language (EL): advanced data access

  • Expressions may also refer to cookies, request parameters, and other data:

    • ${cookie.crumb}

    • ${param.password}

    • ${header[“User-Agent”]}

    • ${pageContext.request.remoteUser}

The jsp expression language el more syntax l.jpg

The JSP Expression Language (EL): more syntax

  • The EL supports

    • Arithmetic${age + 3}

    • Comparisons${age > 21}

    • Equality checks${age = 55}

    • Logical operations${young or beautiful}

    • Emptiness detection${empty a}

      • ‘a’ is empty String (“”), empty List, null, etc. Useful for ${empty param.x}

The jsp expression language uses l.jpg

The JSP Expression Language: Uses

  • JSTL 1.0 introduced the EL, but it could be used only within tags.

  • In JSP 2.0, it can be used almost anywhere

    <font color=”${color}”>

    Hi, ${user}.

    You are <user:age style=”${style}”/> years old.


Tag files nature and purpose l.jpg

Tag Files: nature and purpose

  • Solve difficulty of reusing text/HTML within a tag.

    • And makes it much easier to write simple tags, since you can do so in JSP instead of Java.

  • Stand-alone file with <%@ tag %> directive instead of traditional <%@ page %> directive.

Jsp 2 0 tag files l.jpg

JSP 2.0 tag files

<%@ tag name=”tableTag” %>

<%@ attribute name=”items” %>

<table width=”…” bgcolor=”…”>





<c:forEach var=”i” items=”${items}”>







Using the new tag l.jpg

Using the new tag…

Your shopping cart:

<my:tableTag items=”${cart}” />

Your wish list:

<my:tableTag items=”${wishList}” />

Things we want you to buy:

<my:tableTag items=”${pressuredSales}” />

Old tag handler l.jpg

Old tag handler

Tag handler












Simpletag handler l.jpg

SimpleTag handler

Tag handler








Jsp 2 0 improved xml syntax l.jpg

JSP 2.0: Improved XML syntax

Old style: JSP as document

New style: JSP as namespace

  • Other changes

    • <jsp:element>, <jsp:attribute>

      • Avoids <a href=”<c:url value=”…”/>”/>



Question 3 l.jpg

Question 3

  • What is JSTL? What features does it offer?

Jstl design principles l.jpg

JSTL design principles

  • JSTL 1.0: Keep it simple!

  • Targeted tags

    • Could have a single <go> tag:

      • <go action=“forEach” argument1=“${myData}”>

    • Instead, single-purpose tags, tightly focused

  • Design intended for page author

    • Perhaps something of a fantasy, like the legal “reasonable person.” But a helpful guide nonetheless.

The parable of mike and phillipe l.jpg

The parable of Mike and Phillipe



Credit: Pierre Delisle (spec lead)

Jstl 1 0 features l.jpg

JSTL 1.0 features

  • Control flow

    • Iteration, conditions

  • URL management

    • Retrieve data, add session IDs

  • Text formatting and internationalization

    • Dates and numbers

    • Localized messages

  • XML manipulation

    • XPath, XSLT

  • Database access

    • Queries, updates

Jstl 1 0 libraries l.jpg

JSTL 1.0 libraries

Jstl features managing variables l.jpg

JSTL features:managing variables

  • Outputting values with EL

    <c:out value=”${user.IQ}” />

  • Storing data

    <c:set var=”user”


    // arbitrary text


    Note the use of “var” and “scope”: a JSTL convention

Jstl features iteration l.jpg

JSTL features:iteration

  • Iteration

    <c:forEach items=”${list}”

    begin=”5” end=”20” step=”4”


    <c:out value=”${item}”/>


  • “paging”

Jstl features conditional logic l.jpg

Conditional evaluation

<c:if test=”${a == b}”>

a equals b


Mutually exclusive conditionals


<c:when test=”${a == b}”>

a equals b


<c:when test=”${a == c}”>

a equals c



I don’t know what ’a’ equals.



JSTL features:conditional logic

Jstl features url management l.jpg

JSTL features:URL management

  • Retrieving data

    <c:import var=”cnn”


    • Data exposed as String or Reader

    • All core URLs supported (HTTP, FTP, HTTPS with JSSE)

    • Local, cross-context imports supported

  • Printing URLs

    <c:url value=”/foo.jsp”>

  • Redirection

    <c:redirect url=”/foo.jsp”>

Jstl features text formatting l.jpg

JSTL features:text formatting

  • Locale-sensitive formatting and parsing

    • Numbers

    • Dates

  • Internationalization

    • Message bundles

  • Message argument substitution

    • “Hi {0}. I would like to {1} your money today. I will use it to buy myself a big {2}.”

<fmt:formatNumber type=“currency” value=“${salary}” />

<fmt:message key=“welcome” />

Jstl features xml manipulation l.jpg

JSTL features:XML manipulation

  • Use of XPath to access, display pieces of XML documents

    <c:import url=”http://www.cnn.com/cnn.rss” var=”cnn”/>

    <x:parse xml=”${cnn}” var=“dom”>

    <x:out value=”$dom//item[1]/title”/>

  • Chaining XSLT transformations

    <x:transform xslt=”${xsl2}” />

    <x:transform xml=”${xml}” xslt=”${xsl}” />


Advantages of jstl xml xpath support l.jpg

Advantages of JSTL XML/XPath support

  • Why not always use XSLT?

    • JSTL integrates XPath with convenient, standard access to Java/JSP code.

      • E.g., parse an article URL out of a document, then follow the URL and parse its contents.

    • JSP/JSTL may be more familiar and convenient for simple tasks.

      • Functional versus imperative programming

Jstl features database manipulation l.jpg

JSTL features:database manipulation

  • Queries (and ResultSet caching)

  • Updates / inserts

  • Transactions (<sql:transaction>)

  • Parametric (PreparedStatement) argument substitution (<sql:param>)

  • DataSource-based connection management

<sql:query sql=“SELECT * FROM USERS” var=“result” />

<c:forEach items=“${result.rows}”> … </c:forEach>

Sql tags the debate l.jpg

SQL tags: the debate












Sql tags the expert group s conclusion l.jpg

SQL Tags:The expert group’s conclusion

  • SQL tags are needed because…

    • many nonstandard offerings exist

    • it is not JSTL’s role to dictate a choice of framework

      • As popular as MVC is, it’s not universal.

      • Even in an MVC application, not all data is worth handling carefully.

    • prototyping is important

    • users ask for it!

  • The JSTL specification recommends avoidance of SQL tags in large applications.

Jstl programmer support l.jpg

JSTL programmer support

  • JSTL also supports Java developers

    • Simplifies tag development

    • IteratorTagSupport, ConditionalTagSupport

    • Instead of writing whole tag handler (doStartTag(),doEndTag()), simply override a few methods:

      • protected boolean condition()

      • protected Object next()

    • Still, JSP 2.0 is probably easier.

      • Ugly JSP 1.1 tag protocol  Ugly JSP 1.1 tag protocol with assistance from JSTL 1.0  Nice JSP 2.0 tag protocol.

Jstl programmer support45 l.jpg

JSTL programmer support

  • JSTL API allows registrations of defaults…

    • DataSource

    • Limit on size of results

    • Localization context (Locale, etc.)

    • Time zone

Question 4 l.jpg

Question 4

  • How do the technologies work together?

Models of jsp development l.jpg

“Models” of JSP development

  • Origin of the terms “model 1” and “model 2.”

    • JSP 0.92 spec: “You can apply the JavaServer Pages technology in two ways . . . Model 1: A request sent to a JavaServer Pages file. . . . Model 2: A request sent to a Java Servlet.”

Jstl works with either model l.jpg

JSTL works with either model

  • Core tags, formatting tags are ideal for applications that use either model.

  • XML-manipulation tags are on the borderline. Ideally, they pull data out of XML files that servlets or other back-end logic sends them.

  • SQL tags are probably most useful in model-1 applications.

Simple model 2 example l.jpg

Simple “model 2” example

public void doGet(HttpServletRequest request

HttpServletResponse response) {

// business logic that results in object ’data’

request.setAttribute(”d”, data);




We have some data to display: <b>${d.property1}</b>

  • In this case, the data passed is a simple bean-style object. It could also be an XML document; we’d then use JSTL’s XML-manipulation tags.

Transferring data l.jpg

Transferring data

  • Use XML documents (i.e., DOM objects) and the JSTL <x:*> tags

  • Use JavaBean-style classes

    public class MyData {

    public String getCustomerName() { return X; }

    public Date getCustomerBirthday() { return Y; }



Summary or what s new l.jpg

Summary. Or, what’s new?

  • This was all possible before. What are the benefits of the newer standards and technologies?

    • Easier development

    • Easier debugging

    • Easier maintenance

    • Easier reuse

Slide52 l.jpg


Official JSTL site (spec, implementations)


Quick JSTL reference


Official JSP site


JSP 2.0 JSR (spec currently in Proposed Final Draft)


JSTL in Action


My email address

mailto:[email protected]

Slide53 l.jpg


  • Syntax? Semantics? Other features?

  • Java Community Process procedures, anecdotes?

  • Future directions?

  • Login