
6b46a28bbc4c864676233485215b33bd.ppt
- Количество слайдов: 68
Using JSP 2. 0’s New Features Shawn Bayern Research Programmer, Yale University ¢ JSTL reference-implementation lead ¢ Author, JSTL in Action Web Development with Java. Server Pages ¢
JSTL in Action “A nicely written book. . . beginnerfriendly 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 book’s title aren’t just words, it’s a methodological principle. The discussion concentrates on practice rather than theory and specifications. ” —Java. Ranch. com
JSTL in Action “The jokes seem inappropriate. ” — Internal reviewer
“Regime Change” for JSP ¢ Four key questions to answer today: l What justifies JSP 2. 0? l What are its major new features? l What is JSTL? l What do these new technologies suggest about development patterns and best practices?
Crash course on the J 2 EE Presentation Tier Your web pages Your application JSTL Java. Server Pages (JSP) Java Servlet API Java language
Crash course on the J 2 EE Presentation Tier J 2 EE JSTL Servlets JSP JSTL ¢ Current standards: JSP 1. 2 l Servlet 2. 3 l JSTL 1. 0 l ¢ In a few months: JSP 2. 0 l Servlet 2. 4 l JSTL 1. 1 l
More details about scheduling ¢ ¢ ¢ JSP 2. 0 is currently in Proposed Final Draft (PFD) JSP 2. 0 PFD 2 (second draft) is planned for January 2003. JSP 2. 0, JSTL 1. 1, Servlet 2. 4 released with J 2 EE 1. 4 (probably a few months from now) As of today A few weeks JSP 1. 2 (JSP 2. 0 PFD 2) JSTL 1. 0 (JSP 2. 0 PFD) A few months JSP 2. 0 JSTL 1. 1
What kinds of things go in JSP pages? Scriptlets ¢ <% get. Foo(request); print. Foo(out); String a = ”username”; ¢ %> <% if (a. equals(”pig”) {%> Oink! <% } %> ¢ 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 pages? Tag libraries ¢ <foo: bar/> <c: if test=”${c}”> c is true </c: if> <c: for. Each> Round and round we go </c: for. Each> ¢ ¢ XML tags Invoke Java logic behind the scenes. May access body, e. g. , for iteration, conditional inclusion—or just as arbitrary parameter May access Page. Context Libraries and prefixes
Question 1 ¢ Why JSP 2. 0? (Or, what’s wrong with the current version of JSP? )
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 J 2 EE and Java technologies (Servlets, EJB) ¢
What’s irritating about JSP? ( ) ¢ The tag-extension protocol is too complicated do. Start. Tag() or d f en? r ha , ev o To sling Go do. Init. Body() do. Catch() do. End. Tag() release() Tag handler do. After. Body() do. Finally()
What’s irritating about JSP? ( ) ¢ Also, tags don’t support certain kinds of code reuse. <font color=”<%=status. Color%>”> <% for (…) { %> <%= customer %>: <%= hat. Size %> <% } %> </font> out. println(…); for(…) { out. println(…); … }
What’s bad about JSP? ( ) ¢ The general consensus says… Scriplets They complicate abstraction and code reuse. l They make it harder for nonprogrammers to maintain pages l
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? ¢ ¢ Expression language (EL) Tag files Simplified Tag API (Simple. Tag 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 ¢ The major goal: simplicity. l ¢ The language should be usable by nonprogrammers. Inspirations: Java. Script, XPath l 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?
How easy is XPath? //foo=’bar’ <a> <b> <c> <foo>hmm</foo> </c> <d> <foo>bar</foo> </d> </a>
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. ”
How easy is XPath? //foo=’bar’ True! <a> <b> <c> <foo>hmm</foo> </c> <d> <foo>bar</foo> </d> </a>
ECMAScript (age + 3) ¢ Page 62 of 188: The Addition operator ( + ) 29. One-half or self-employment tax. The addition operator either performs string concatenationof numeric addition. The production Additive. Expression : Additive. Expression + Multiplicative. Expression is evaluated as Attach Schedule SE. follows: 30. Self-employed health insurance 1. Evaluate Additive. Expression. 2. Call Get. Value(Result(1)). deduction (see page 33) 3. Evaluate Multiplicative. Expression. 31. Self-employed SEP, SIMPLE, and 4. Call Get. Value(Result(3)). 5. Call To. Primitive(Result(2)). qualified plans 6. Call To. Primitive(Result(4)). 32. Penalty on early withdrawal step differs 7. If Type(Result(5)) is String or Type(Result(6)) is String, go to step 12. (Note that thisof savings from step 3 in the comparison algorithm for the relational paid 33. Alimony operators, by using or instead of and. ) 8. Call To. Number(Result(5)). 34. Add lines 23 through 33 a 9. Call To. Number(Result(6)). 10. Apply the addition operation to Result(8)Subtract line 34 note below (11. 6. 3). This is 35. and Result(9). See the from line 22. 11. Return Result(10). your adjusted gross income. 12. Call To. String(Result(5)). 13. Call To. String(Result(6)). 14. Concatenate Result(12) followed by Result(13). 15. Return Result(14).
The JSP Expression Language (EL): Key syntax ¢ Expressions appear between ${ and }. l l ¢ Note that ${ and } may contain whole expressions, not just variable names, as in the Bourne shell (and its dozen derivatives. ) E. g. , ${my. Expression + 2} Expressions’ default targets are scoped attributes (page, request, session, application) l ${user} ≡ page. Context. find. Attribute(“user”)
The JSP Expression Language (EL): Key syntax ¢ The . and [] operators refer to Java. Bean-style properties and Map elements: l ${user. get. Address} can resolve to ((User) page. Context. get. Attribute(”user”)). get. Address() ¢ Note l 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 ¢ Expressions may also refer to cookies, request parameters, and other data: ${cookie. color. Preference} l ${param. password} l ${header[“User-Agent”]} l ${page. Context. request. remote. User} l ${init. Param. database. Password} l
The JSP Expression Language (EL): more syntax ¢ The EL supports Arithmetic l Comparisons l Equality checks l Logical operations l Grouping l Emptiness detection l ${age + 3} ${age > 18} ${age = 55} ${young or beautiful} ${(a+b) * c} ${empty a} • ‘a’ is empty String (“”), empty List, null, etc. Useful for ${empty param. x}
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}”/> </font> years old.
EL functions: new in JSP 2. 0 ¢ The expression language does not support methods. l ¢ Why not? Instead, it lets you register static functions in a tag-library descriptor (TLD)
Registering an EL function <taglib>. . . <function> <name>is. Nejug. Member</name> <function-class> org. nejug. Util </function-class> <function-signature> Boolean is. Nejug. Member(String) </function-signature> </function> </taglib> public static Boolean is. Nejug. Member(String x);
Using an EL function ${my. Lib: is. Nejug. Member(user)} <my. Lib: print. Status member=”${is. Nejug. Member(user)}” />
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: Java. Server Faces; opensource projects; your own products.
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. l ¢
The role of tag files JSP Page. jsp Servlet <%@ page %> JSP tag file. tag <%@ tag %> Tag-handler class
JSP 2. 0 tag files <%@ tag name=”table. Tag” %> <%@ attribute name=”items” %> <table width=”…” bgcolor=”…”> <th> <td>Name</td> <td>IQ</td> </th> <c: for. Each var=”i” items=”${items}”> <tr> <td>${i. full. Name}</td> <td>${i. IQ}</td> </tr> </c: for. Each> </table>
Using the new tag… Your shopping cart: <my: table. Tag items=”${cart}” /> Your wish list: <my: table. Tag items=”${wish. List}” /> Things we want you to buy: <my: table. Tag items=”${pressured. Sales}” />
Tag-file directives ¢ <%@ tag %> Just as boring as <%@ page %> l Primarily for bookkeeping, tool support l E. g. , l • description, large-icon, small-icon • is. Scripting. Enabled • is. ELEnabled
Tag-file directives ¢ <%@ attribute %> l Declares attributes for the tag you’re creating <%@ attribute name=“foo” required=“true” rtexprvalue=“false” %> l Provides support for “fragments” • Like Dynamo’s “OPARAMS” (ATG) <%@ attribute name=“foo” fragment=“true” %> … <jsp: invoke fragment=“foo”> <jsp: param name=“user. Level” value=“expert” > </jsp: invoke>
Using fragments <my. Tag: print. Table data=“${my. Data}”> <jsp: attribute name=“table. Separator”> <c: if value=“${param. browser. Type eq ‘text. Only’}”> ------</c: if> <c: if value=“${param. browser. Type eq ‘full. Html’}> <hr /> </c: if> </jsp: attribute> … </my. Tag>
Old tag handler Tag attributes do. Start. Tag() do. Catch() Tag body do. End. Tag() release() Tag handler do. Init. Body() do. After. Body() do. Finally()
Simple. Tag handler Tag attributes Tag body do. Tag() Tag handler (no scriptlets)
Using Simple. Tag ¢ Example public class My. Tag extends Simple. Tag. Support { public void do. Tag() { Jsp. Writer out = get. Jsp. Context(). get. Out(); out. println(”My body is…”); out. print(get. Jsp. Body()); out. println(”attribute=” + attribute); } public void set. Attribute(String x) { this. attribute = x}; }
Other changes to tagextension API ¢ Dynamic attributes l l Ideal for tags that “wrap” other tags, such as HTML tags How to use • Implement Dynamic. Attributes interface • Define public void set. Dynamic. Attribute( String uri, String local. Name, Object value) to accept the attributes, and do whatever you want with them.
JSP 2. 0: Improved XML syntax Old style: JSP as document <jsp: root> New style: JSP as namespace xmlns: jsp=“http: //java. sun. com/JSP/Page”
Question 3 ¢ What is JSTL? What features does it offer?
JSTL design principles JSTL 1. 0 / 1. 1: Keep it simple! ¢ Targeted tags ¢ l Could have a single <go> tag: • <go action=“for. Each” argument 1=“${my. Data}”> l ¢ Instead, single-purpose tags, tightly focused Design intended for page author l Perhaps something of a fantasy, like the legal “reasonable person. ” But a helpful guide nonetheless.
The parable of Mike and Phillipe Mike Credit: Pierre Delisle (spec lead) Phillipe
JSTL 1. 0 features ¢ ¢ ¢ Control flow l Iteration, conditions URL management l Retrieve data, add session IDs Text formatting and internationalization l Dates and numbers l Localized messages XML manipulation l XPath, XSLT Database access l Queries, updates
JSTL 1. 0 libraries Library features Recommended prefix Core (control flow, URLs, variable access) Text formatting c XML manipulation x Database access sql fmt
JSTL features: managing variables ¢ Outputting 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
JSTL features: iteration ¢ Iteration <c: for. Each items=”${list}” begin=” 5” end=” 20” step=” 4” var=”item”> <c: out value=”${item}”/> </c: for. Each> ¢ “paging”
JSTL features: conditional logic ¢ Conditional 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>
JSTL features: URL management ¢ Retrieving data <c: import var=”cnn” url=”http: //www. cnn. com/cnn. rss”/> l l l ¢ 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 ¢ Locale-sensitive formatting and parsing l l ¢ <fmt: format. Number type=“currency” value=“${salary}” /> Internationalization l ¢ Numbers Dates Message bundles <fmt: message key=“welcome” /> Message argument substitution l “Hi {0}. I would like to {1} your money today. I will use it to buy myself a big {2}. ”
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=”${xsl 2}” /> <x: transform xml=”${xml}” xslt=”${xsl}” /> </x: transform>
Advantages of JSTL XML/XPath support ¢ Why not always use XSLT? l 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. l JSP/JSTL may be more familiar and convenient for simple tasks. • Functional versus imperative programming
JSTL vs. XSLT example <title><x: out select=". "/></title> <summary> <%-- Retrieve and print the article lead --%> <c: set var="article. URL"> <x: out select=". /@href"/> </c: set> <c: import var="article. Text" url="${article. URL}"/> <x: parse … /> <x: out … /> </summary>
JSTL features: database manipulation ¢ Queries (and Result. Set caching) <sql: query sql=“SELECT * FROM USERS” var=“result” /> <c: for. Each items=“${result. rows}”> … </c: for. Each> ¢ ¢ Updates / inserts Transactions (<sql: transaction>) Parametric (Prepared. Statement) argument substitution (<sql: param>) Data. Source-based connection management
SQL tags: the debate Tag library Database JSP page Back-end Java code Tag library
SQL Tags: The expert group’s conclusion ¢ SQL tags are needed because… many nonstandard offerings exist l it is not JSTL’s role to dictate a choice of framework l • As popular as MVC is, it’s not universal. • Even in an MVC application, not all data is worth handling carefully. prototyping is important l users ask for it! l ¢ The JSTL specification recommends avoidance of SQL tags in large applications.
JSTL programmer support ¢ JSTL also supports Java developers l l l Simplifies tag development Iterator. Tag. Support, Conditional. Tag. Support Instead of writing whole tag handler (do. Start. Tag(), do. End. Tag()), simply override a few methods: • protected boolean condition() • protected Object next() l Still, JSP 2. 0 is probably easier. • Ugly JSP 1. 1 tag protocol with assistance from JSTL 1. 0 Nice JSP 2. 0 tag protocol.
JSTL programmer support ¢ JSTL API allows registrations of defaults… Data. Source l Limit on size of results l Localization context (Locale, etc. ) l Time zone l
Question 4 ¢ How do the technologies work together?
“Models” of JSP development ¢ Origin of the terms “model 1” and “model 2. ” l JSP 0. 92 spec: “You can apply the Java. Server Pages technology in two ways. . . Model 1: A request sent to a Java. Server Pages file. . Model 2: A request sent to a Java Servlet. ”
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 public void do. Get(Http. Servlet. Request request Http. Servlet. Response response) { // business logic that results in object ’data’ request. set. Attribute(”d”, data); sc. get. Request. Dispatcher(”/view. jsp”); } view. jsp We have some data to display: <b>${d. property 1}</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 Use XML documents (i. e. , DOM objects) and the JSTL <x: *> tags ¢ Use Java. Bean-style classes ¢ public class My. Data { public String get. Customer. Name() { return X; } public Date get. Customer. Birthday() { return Y; } } ${my. Data. Instance. customer. Name}
Summary. Or, what’s new? ¢ This was all possible before. What are the benefits of the newer standards and technologies? Easier development l Easier debugging l Easier maintenance l Easier reuse l
URLs Official JSTL site (spec, implementations) http: //java. sun. com/products/jstl Quick JSTL reference http: //www. manning. com/bayern/appendix. A. 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 mailto: bayern@essentially. net
Q&A ¢ Syntax? Semantics? Other features? ¢ Java Community Process procedures, anecdotes? ¢ Future directions?
6b46a28bbc4c864676233485215b33bd.ppt