Using JSP 2.0 - PowerPoint PPT Presentation

About This Presentation
Title:

Using JSP 2.0

Description:

The words in action' in the book's title aren't just words, it's a methodological principle. ... Too hard for Gosling, even? What's irritating about JSP? ... – PowerPoint PPT presentation

Number of Views:139
Avg rating:3.0/5.0
Slides: 69
Provided by: ShawnB57
Category:
Tags: jsp | gosling | using

less

Transcript and Presenter's Notes

Title: Using JSP 2.0


1
Using JSP 2.0sNew Features
  • Shawn Bayern
  • Research Programmer, Yale University
  • JSTL reference-implementation lead
  • Author, JSTL in Action
  • Web Development with JavaServer
    Pages

2
JSTL in Action
A nicely written book...beginner-friendly on all
levels... It will be a long time before I
forget the author's definition of scope that
compared it to flying rats... The words in
action in the books title arent just words,
its a methodological principle. The discussion
concentrates on practice rather than theory and
specifications. JavaRanch.com
3
JSTL in Action
The jokes seem inappropriate. Internal
reviewer
4
Regime Change for JSP
  • 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?

5
Crash course on the J2EE Presentation Tier
Your application
Your web pages
JSTL
JavaServer Pages (JSP)
Java Servlet API
Java language
6
Crash course on the J2EE Presentation Tier
J2EE
JSTL
Servlets
JSP
JSTL
  • Current standards
  • JSP 1.2
  • Servlet 2.3
  • JSTL 1.0
  • In a few months
  • JSP 2.0
  • Servlet 2.4
  • JSTL 1.1

7
More details about scheduling
  • JSP 2.0 is currently in Proposed Final Draft
    (PFD)
  • JSP 2.0 PFD2 (second draft) is planned for
    January 2003.
  • JSP 2.0, JSTL 1.1, Servlet 2.4 released with J2EE
    1.4 (probably a few months from now)

As of today
A few weeks
A few months
JSP 1.2 JSTL 1.0 (JSP 2.0 PFD)
(JSP 2.0 PFD2)
JSP 2.0 JSTL 1.1
8
What kinds of things go in JSP pages?
  • Scriptlets
  • lt
  • getFoo(request)
  • printFoo(out)
  • String a username
  • gt
  • lt if (a.equals(pig) gt
  • Oink!
  • lt gt
  • Java (and more?) embedded within template text
  • Access to implicit objects request, response,
    etc.
  • Conditional blocks, loopsmanually constructed

9
What kinds of things go in JSP pages?
  • Tag libraries
  • ltfoobar/gt
  • ltcif testcgt
  • c is true
  • lt/cifgt
  • ltcforEachgt
  • Round and round we go
  • lt/cforEachgt
  • XML tags
  • Invoke Java logic behind the scenes.
  • May access body, e.g., for iteration, conditional
    inclusionor just as arbitrary parameter
  • May access PageContext
  • Libraries and prefixes

10
Question 1
  • Why JSP 2.0?
  • (Or, whats wrong with the current version of
    JSP?)

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

12
Whats irritating about JSP?
(?)
  • The tag-extension protocol is too complicated

Tag handler
doStartTag()
doEndTag()
?
Too hard for Gosling, even?
doInitBody()
doAfterBody()
doCatch()
doFinally()
release()
13
Whats irritating about JSP?
(?)
  • Also, tags dont support certain kinds of code
    reuse.
  • ltfont colorltstatusColorgtgt
  • lt for () gt
  • lt customer gt lt hatSize gt
  • lt gt
  • lt/fontgt

?
out.println() for() out.println()
14
Whats bad about JSP? (?)
  • The general consensus says
  • Scriplets
  • They complicate abstraction and code reuse.
  • They make it harder for nonprogrammers to
    maintain pages

15
Question 2
  • What new features does JSP 2.0 offer?
  • (Or, how does it fix the issues we just raised?)

16
How does JSP 2.0 address these issues?
  • Expression language (EL)
  • Tag files
  • Simplified Tag API (SimpleTag versus Tag)
  • Improved XML syntax
  • Also, though its not really part of JSP,
  • JSTL improves things too.
  • The end result
  • JSP pages become easier to write and maintain.

17
The JSP Expression Language (EL) Goals and
principles
  • The major goal simplicity.
  • The language should be usable by nonprogrammers.
  • Inspirations JavaScript, XPath
  • But its much simpler than even these basic
    expression languages.
  • Quick what does //foo bar mean in XPath?
  • Or what happens with age 3 in ECMAScript?

18
How easy is XPath?
  • //foobar
  • ltagt
  • ltbgt
  • ltcgt
  • ltfoogthmmlt/foogt
  • lt/cgt
  • ltdgt
  • ltfoogtbarlt/foogt
  • lt/dgt
  • lt/agt

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

20
How easy is XPath?
  • //foobar
  • ltagt
  • ltbgt
  • ltcgt
  • ltfoogthmmlt/foogt
  • lt/cgt
  • ltdgt
  • ltfoogtbarlt/foogt
  • lt/dgt
  • lt/agt

True!
21
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
  • follows
  • 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)).

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.
22
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)
  • user pageContext.findAttribute(user)

23
The JSP Expression Language (EL) Key syntax
  • The . and operators refer to JavaBean-style
    properties and Map elements
  • user.getAddress can resolve to
  • ((User) pageContext.getAttribute(user)).getAdd
    ress()
  • 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.)

24
The JSP Expression Language (EL) advanced data
access
  • Expressions may also refer to cookies, request
    parameters, and other data
  • cookie.colorPreference
  • param.password
  • headerUser-Agent
  • pageContext.request.remoteUser
  • initParam.databasePassword

25
The JSP Expression Language (EL) more syntax
  • The EL supports
  • Arithmetic age 3
  • Comparisons age gt 18
  • Equality checks age 55
  • Logical operations young or beautiful
  • Grouping (ab) c
  • Emptiness detection empty a
  • a is empty String (), empty List, null, etc.
    Useful for empty param.x

26
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
  • ltfont colorcolorgt
  • Hi, user.
  • You are ltuserage stylestyle/gt
    years old.
  • lt/fontgt

27
EL functions new in JSP 2.0
  • The expression language does not support methods.
  • Why not?
  • Instead, it lets you register static functions in
    a tag-library descriptor (TLD)

28
Registering an EL function
  • lttaglibgt
  • ...
  • ltfunctiongt
  • ltnamegtisNejugMemberlt/namegt
  • ltfunction-classgt
  • org.nejug.Util
  • lt/function-classgt
  • ltfunction-signaturegt
  • Boolean isNejugMember(String)
  • lt/function-signaturegt
  • lt/functiongt
  • lt/taglibgt

public static Boolean isNejugMember(String x)
29
Using an EL function
  • myLibisNejugMember(user)
  • ltmyLibprintStatus
  • memberisNejugMember(user)
  • /gt

30
EL API
  • JSTL 1.0 introduced the EL, but not a standard
    API to access its interpreter.
  • JSP 2.0 offers standard API under
    javax.servlet.jsp.el package.
  • Uses JavaServer Faces open-source projects
    your own products.

31
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 lt_at_ tag gt directive
    instead of traditional lt_at_ page gt
    directive.

32
The role of tag files
JSP Page .jsp lt_at_ page gt
Servlet
JSP tag file .tag lt_at_ tag gt
Tag-handler class
33
JSP 2.0 tag files
  • lt_at_ tag nametableTag gt
  • lt_at_ attribute nameitems gt
  • lttable width bgcolorgt
  • ltthgt
  • lttdgtNamelt/tdgt
  • lttdgtIQlt/tdgt
  • lt/thgt
  • ltcforEach vari itemsitemsgt
  • lttrgt
  • lttdgti.fullNamelt/tdgt
  • lttdgti.IQlt/tdgt
  • lt/trgt
  • lt/cforEachgt
  • lt/tablegt

34
Using the new tag
  • Your shopping cart
  • ltmytableTag itemscart /gt
  • Your wish list
  • ltmytableTag itemswishList /gt
  • Things we want you to buy
  • ltmytableTag itemspressuredSales /gt

35
Tag-file directives
  • lt_at_ tag gt
  • Just as boring as lt_at_ page gt
  • Primarily for bookkeeping, tool support
  • E.g.,
  • description, large-icon, small-icon
  • isScriptingEnabled
  • isELEnabled

36
Tag-file directives
  • lt_at_ attribute gt
  • Declares attributes for the tag youre creating
  • Provides support for fragments
  • Like Dynamos OPARAMS (ATG)

lt_at_ attribute namefoo requiredtrue
rtexprvaluefalse gt
lt_at_ attribute namefoo fragmenttrue
gt ltjspinvoke fragmentfoogt ltjspparam
nameuserLevel valueexpert gt lt/jspinvokegt
37
Using fragments
  • ltmyTagprintTable datamyDatagt
  • ltjspattribute nametableSeparatorgt
  • ltcif valueparam.browserType eq
    textOnlygt
  • - - - - - - -
  • lt/cifgt
  • ltcif valueparam.browserType eq
    fullHtmlgt
  • lthr /gt
  • lt/cifgt
  • lt/jspattributegt
  • lt/myTaggt

38
Old tag handler
Tag handler
doStartTag()
doEndTag()
Tag body
Tag attributes
?
doInitBody()
doAfterBody()
doCatch()
doFinally()
release()
39
SimpleTag handler
Tag handler
doTag()
Tag body (no scriptlets)
Tag attributes
?
40
Using SimpleTag
  • Example

public class MyTag extends SimpleTagSupport
public void doTag() JspWriter out
getJspContext().getOut() out.println(My
body is) out.print(getJspBody())
out.println(attribute attribute)
public void setAttribute(String x)
this.attribute x
41
Other changes to tag-extension API
  • Dynamic attributes
  • Ideal for tags that wrap other tags, such as
    HTML tags
  • How to use
  • Implement DynamicAttributes interface
  • Define
  • public void setDynamicAttribute(
  • String uri, String localName, Object value)
  • to accept the attributes, and do whatever you
    want with them.

42
JSP 2.0 Improved XML syntax
  • Old style JSP as document
  • New style JSP as namespace

ltjsprootgt
xmlnsjsphttp//java.sun.com/JSP/Page
43
Question 3
  • What is JSTL? What features does it offer?

44
JSTL design principles
  • JSTL 1.0 / 1.1 Keep it simple!
  • Targeted tags
  • Could have a single ltgogt tag
  • ltgo actionforEach argument1myDatagt
  • 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.

45
The parable of Mike and Phillipe
Mike
Phillipe
Credit Pierre Delisle (spec lead)
46
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

47
JSTL 1.0 libraries

Library features Recommended prefix
Core (control flow, URLs, variable access) c
Text formatting fmt
XML manipulation x
Database access sql
48
JSTL featuresmanaging variables
  • Outputting values with EL
  • ltcout valueuser.IQ /gt
  • Storing data
  • ltcset varuser
  • scopesessiongt
  • // arbitrary text
  • lt/csetgt
  • Note the use of var and scope a JSTL
    convention

49
JSTL featuresiteration
  • Iteration
  • ltcforEach itemslist
  • begin5 end20 step4
  • varitemgt
  • ltcout valueitem/gt
  • lt/cforEachgt
  • paging

50
JSTL featuresconditional logic
  • Conditional evaluation
  • ltcif testa bgt
  • a equals b
  • lt/cifgt
  • Mutually exclusive conditionals
  • ltcchoosegt
  • ltcwhen testa bgt
  • a equals b
  • lt/cwhengt
  • ltcwhen testa cgt
  • a equals c
  • lt/cwhengt
  • ltcotherwisegt
  • I dont know what a equals.
  • lt/cotherwisegt
  • lt/cchoosegt

51
JSTL featuresURL management
  • Retrieving data
  • ltcimport varcnn
  • urlhttp//www.cnn.com/cnn.rss/gt
  • Data exposed as String or Reader
  • All core URLs supported (HTTP, FTP, HTTPS with
    JSSE)
  • Local, cross-context imports supported
  • Printing URLs
  • ltcurl value/foo.jspgt
  • Redirection
  • ltcredirect url/foo.jspgt

52
JSTL featurestext 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.

ltfmtformatNumber typecurrency
valuesalary /gt
ltfmtmessage keywelcome /gt
53
JSTL featuresXML manipulation
  • Use of XPath to access, display pieces of XML
    documents
  • ltcimport urlhttp//www.cnn.com/cnn.rss
    varcnn/gt
  • ltxparse xmlcnn vardomgt
  • ltxout valuedom//item1/title/gt
  • Chaining XSLT transformations
  • ltxtransform xsltxsl2 /gt
  • ltxtransform xmlxml xsltxsl /gt
  • lt/xtransformgt

54
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

55
JSTL vs. XSLT example
  • lttitlegtltxout select"."/gtlt/titlegt
  • ltsummarygt
  • lt-- Retrieve and print the article lead --gt
  • ltcset var"articleURL"gt
  • ltxout select"./_at_href"/gt
  • lt/csetgt
  • ltcimport var"articleText" url"articleURL"/gt
  • ltxparse /gt
  • ltxout /gt
  • lt/summarygt

56
JSTL featuresdatabase manipulation
  • Queries (and ResultSet caching)
  • Updates / inserts
  • Transactions (ltsqltransactiongt)
  • Parametric (PreparedStatement) argument
    substitution (ltsqlparamgt)
  • DataSource-based connection management

ltsqlquery sqlSELECT FROM USERS
varresult /gt ltcforEach itemsresult.rowsgt
lt/cforEachgt
57
SQL tags the debate
JSP page
Back-end Java code
Tag library
Database
Tag library
JSTL SQL tags
58
SQL TagsThe expert groups conclusion
  • SQL tags are needed because
  • many nonstandard offerings exist
  • it is not JSTLs role to dictate a choice of
    framework
  • As popular as MVC is, its 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.

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

60
JSTL programmer support
  • JSTL API allows registrations of defaults
  • DataSource
  • Limit on size of results
  • Localization context (Locale, etc.)
  • Time zone

61
Question 4
  • How do the technologies work together?

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

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

64
Simple model 2 example
  • public void doGet(HttpServletRequest request
  • HttpServletResponse response)
  • // business logic that results in object
    data
  • request.setAttribute(d, data)
  • sc.getRequestDispatcher(/view.jsp)
  • view.jsp
  • We have some data to display ltbgtd.property1lt/
    bgt
  • In this case, the data passed is a simple
    bean-style object. It could also be an XML
    document wed then use JSTLs XML-manipulation
    tags.

65
Transferring data
  • Use XML documents (i.e., DOM objects) and the
    JSTL ltxgt tags
  • Use JavaBean-style classes
  • public class MyData
  • public String getCustomerName() return X
  • public Date getCustomerBirthday() return
    Y
  • myDataInstance.customerName

66
Summary. Or, whats new?
  • This was all possible before. What are the
    benefits of the newer standards and technologies?
  • Easier development
  • Easier debugging
  • Easier maintenance
  • Easier reuse

67
URLs
  • Official JSTL site (spec, implementations)
  • http//java.sun.com/products/jstl
  • Quick JSTL reference
  • http//www.manning.com/bayern/appendixA.pdf
  • Official JSP site
  • http//java.sun.com/products/jsp
  • JSP 2.0 JSR (spec currently in Proposed Final
    Draft)
  • http//www.jcp.org/jsr/detail/152.jsr
  • JSTL in Action
  • http//www.jstlbook.com/
  • My email address
  • mailtobayern_at_essentially.net

68
QA
  • Syntax? Semantics? Other features?
  • Java Community Process procedures, anecdotes?
  • Future directions?
Write a Comment
User Comments (0)
About PowerShow.com