32

Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

Embed Size (px)

Citation preview

Page 1: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages
Page 2: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

Organization of the platformYour application

Java language

Java Servlet API

JavaServer Pages (JSP)

JSTL

Yourweb pages

Page 3: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

What’s irritating about Custom Tags?The tag-extension protocol is too complicated

Tag handler

doStartTag() doEndTag()

doCatch() doFinally()

doInitBody() doAfterBody()

release()

Too hard for

Gosling,

even?

Page 4: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

What’s irritating about JSP? Also, tags don’t support certain kinds of code

reuse.

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

<% for (…) { %>

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

<% } %>

</font>out.println(…);

for(…) {

out.println(…);

}

Page 5: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

What’s bad about JSP? ()

The general consensus says…

Scriplets

They complicate abstraction and code reuse.They make it harder for nonprogrammers to

maintain pages

Page 6: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

JSP 2.0Sun introduced the solution to these

problems in JSP 2.0.It addresses theses issues by introducing

Expression languageTag filesSimplified Tag API (SimpleTag versus Tag)Improved XML syntaxJSTL, although it is not part of JSP specificiation.

Page 7: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

JSP Expression LanguageJSP became beautiful after this The motivation is to lose scriplets whatsoever

.Also non java programmers should be able to

use it easily, because it is just an expression language.

It was inspired by xpath and java script except it is much easier than any of them

Page 8: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

EL syntaxExpressions appear between ${ and }.

Note that ${ and } may contain whole expressions, not just variable names

E.g., ${myExpression + 2}

Access JavaBean properties using . (dot) ${book.title} translates to book.getTitle()

Access to Array and Collection elements using collection[]Access to a Map value by key using map[“key”]

Page 9: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

EL syntaxEL searches each scope area if a

scope isn’t specifiedSpecific scope areas can be used:

${pageScope.title}${requestScope.title}${sessionScope.title}${applicationScope.title}

${duck.beakColor} can resolve to ((Duck) pageContext.getAttribute(”duck”)).getBeakColor()

Automatic Casting, wow

Page 10: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

EL OperatorsArithmetic

+, -, *, / (or div), % (or mod) – note on XPath Relational

== (or eq), != (or ne), < (or lt) > (or gt), <= (or le), >= (or ge)

Logical&& (or and), || (or or), ! (or not)

Validationempty

null values Collections or Arrays that are empty Strings that evaluate to “”

Page 11: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

EL Operators (Examples)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}

Page 12: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

Implicit objects in ELParam and paramvalues

Access HTTP request parametersExample: ${param.password}

Header and headervaluesRequest header information

Example: ${header[“User-Agent”]}Initparam (for the context init parameters of

the webapp)Example: $

{pageContext.request.remoteUser}Cookies

Example: ${cookie.crumb}

Page 13: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

EL: 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.

</font>

Page 14: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

JSTLJSP Standard Tag LibrarySet of tags that should be available in all

compliant JSP containersPromotes rapid application development at

the web page layer

Page 15: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

Why JSTL?A big reason is that writing your own

custom actions, or tags, can be a painThere was lots of reinventing the

wheel going on, for tasks like displaying a date in a special format

Many open source libraries sprung up, but there was still no standard

This fueled the fire behind JSTL

Page 16: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

JSTL: FeaturesControl flow

Iteration, conditionsURL management

Retrieve data, add session IDsText formatting and internationalization

Dates and numbersLocalized messages

XML manipulationXPath, XSLT

Database accessQueries, updates

(you do not need to write java any more )

Page 17: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

JSTL: Libraries

Library features Recommended prefix

Core (control flow, URLs, variable access)

c

Text formatting fmt

XML manipulation x

Database access sql

Page 18: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

Managing variablesOutputting values with EL

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

Storing data<c:set var=”user” scope=”session”> // arbitrary text</c:set>

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

Page 19: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

IterationA loop with a start, end, and step (typical for statement)

<c:forEach var="name" varStatus="name" begin="expression" end="expression" step="expression"> body content</c:forEach>

A loop using an Iterator for a collection

<c:forEach var="name" items="expression" varStatus="name" begin="expression" end="expression" step="expression"> body content</c:forEach>

Page 20: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

Example<table> <tr><th>Value</th><th>Square</th></tr> <c:forEach var="x" begin="0" end="10" step="2"> <tr> <td>${x}</td> <td>${x * x}</td> </tr> </c:forEach></table>

Page 21: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

Conditional logicConditional evaluation

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

Mutually exclusive conditionals

<c:choose> <c:when test=”${a == b}”> a equals b </c:when> <c:when test=”${a == c}”> a equals c </c:when> <c:otherwise> I don’t know what ’a’ equals. </c:otherwise></c:choose>

Page 22: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

Example<c:choose> <c:when test="${pageContext.request.scheme eq 'http'}"> This is an insecure Web session. </c:when> <c:when test="${pageContext.request.scheme eq 'https'}"> This is a secure Web session. </c:when> <c:otherwise> You are using an unrecognized Web protocol. How did this happen?!

</c:otherwise></c:choose>

Page 23: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

URL managementRetrieving data<c:import var=”cnn”

url=”http://www.cnn.com/cnn.rss”/>

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

Page 24: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

Text formattingLocale-sensitive formatting and parsing

NumbersDates

InternationalizationMessage 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” />

Page 25: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

Example<table><fmt:timeZone value="US/Eastern"><c:forEach items="${entryList}" var="blogEntry" varStatus="status"> <c:if test="${status.first}"> <tr> <td align="left" class="blogDate"> <fmt:formatDate value="${blogEntry.created}" dateStyle="full"/> </td> </tr> </c:if> <tr> <td align="left" class="blogTitle">${blogEntry.title}</td> </tr> <tr> <td align="left" class="blogText">${blogEntry.text} <font class="blogPosted"> [Posted <fmt:formatDate value="${blogEntry.created}" pattern="h:mm a zz"/>] </font> </td> </tr></c:forEach></fmt:timeZone></table>

Page 26: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

database manipulationQueries (and ResultSet caching)

Updates / insertsTransactions (<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>

Page 27: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

XML manipulationUse 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}” /></x:transform>

Page 28: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

Why Not XSLTJSTL 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

Page 29: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

Adding New TagThere are two ways to add news

tagsExtend the JSTL and override methods

Define Tag files (This is much easier, so we gone study this )

Page 30: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

Tag FilesSolve 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.

Page 31: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

Tag Files<%@ tag name=”tableTag” %><%@ attribute name=”items” %>

<table width=”…” bgcolor=”…”> <th> <td>Name</td> <td>IQ</td> </th> <c:forEach var=”i” items=”${items}”> <tr> <td>${i.fullName}</td> <td>${i.IQ}</td> </tr> </c:forEach></table>

Page 32: Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

Using 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}” />