Скачать презентацию JSP 2 0 and JSTL Principles and Patterns Скачать презентацию JSP 2 0 and JSTL Principles and Patterns

3e68300f705539b0f653a5d155c8879f.ppt

  • Количество слайдов: 53

JSP 2. 0 and JSTL: Principles and Patterns Shawn Bayern Research Programmer, Yale University 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 Java. Server Pages ¢

The J 2 EE Presentation Tier ¢ Four key questions to answer today: l The J 2 EE Presentation Tier ¢ 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 J 2 EE JSTL Servlets 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

Crash course on the J 2 EE presentation tier ¢ Servlets l ¢ Java. Crash course on the J 2 EE presentation tier ¢ Servlets l ¢ Java. Server Pages (JSP) l l ¢ Java classes that handle requests by producing responses (e. g. , HTTP requests and responses) HTML-like pages with some dynamic content. They turn into servlets automatically. JSP Standard Tag Library (JSTL) l l Set of standard components for JSP. It is used inside JSP pages.

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

What kinds of things go in JSP pages? Scriptlets ¢ <% get. Foo(request); print. What kinds of things go in JSP pages? Scriptlets ¢ <% get. Foo(request); print. Foo(out); String a = ”goat”; ¢ %> <% 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: What kinds of things go in JSP pages? Tag libraries ¢ 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 Page. Context Libraries and prefixes

Question 1 ¢ Why JSP 2. 0? (Or, what’s wrong with the current version 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 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. 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 What’s irritating about JSP? ( ) ¢ Also, tags don’t support certain kinds of code reuse. ”> <% for (…) { %> <%= customer %>: <%= hat. Size %> <% } %> out. println(…); for(…) { out. println(…); … }

What’s bad about JSP? ( ) ¢ The general consensus says… Scriplets They complicate 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 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 Tag files How does JSP 2. 0 address these issues? ¢ ¢ Expression language 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 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?

XPath (//foo = ‘bar’) ¢ “If one object to be compared is a node-set 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) ¢ Page 62 of 188: The Addition operator ( + 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 }. 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 ${duck} ≡ page. Context. find. Attribute(“duck”)

The JSP Expression Language (EL): Key syntax ¢ The. and [] operators refer to The JSP Expression Language (EL): Key syntax ¢ The. and [] operators refer to Java. Bean-style properties and Map elements: l ${duck. beak. Color} can resolve to ((Duck) page. Context. get. Attribute(”duck”)). get. Beak. Colo r() ¢ Note the automatic type-cast. l 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 The JSP Expression Language (EL): advanced data access ¢ Expressions may also refer to cookies, request parameters, and other data: ${cookie. crumb} l ${param. password} l ${header[“User-Agent”]} l ${page. Context. request. remote. User} l

The JSP Expression Language (EL): more syntax ¢ The EL supports Arithmetic l Comparisons The JSP Expression Language (EL): more syntax ¢ The EL supports Arithmetic l Comparisons l Equality checks l Logical operations l Emptiness detection l ${age + 3} ${age > 21} ${age = 55} ${young or beautiful} ${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 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 ¢ Hi, ${user}. You are years old.

Tag Files: nature and purpose ¢ Solve difficulty of reusing text/HTML within a tag. 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 ¢

JSP 2. 0 tag files <%@ tag name=”table. Tag” %> <%@ attribute name=”items” %> JSP 2. 0 tag files <%@ tag name=”table. Tag” %> <%@ attribute name=”items” %>

Name IQ
${i. full. Name} ${i. IQ}

Using the new tag… Your shopping cart: <my: table. Tag items=”${cart}” /> Your wish Using the new tag… Your shopping cart: Your wish list: Things we want you to buy:

Old tag handler Tag attributes do. Start. Tag() do. Catch() Tag body do. End. 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) Simple. Tag handler Tag attributes Tag body do. Tag() Tag handler (no scriptlets)

JSP 2. 0: Improved XML syntax Old style: JSP as document <jsp: root> New JSP 2. 0: Improved XML syntax Old style: JSP as document New style: JSP as namespace xmlns: jsp=“http: //java. sun. com/JSP/Page” ¢ Other changes l , • Avoids ”/>

Question 3 ¢ What is JSTL? What features does it offer? Question 3 ¢ What is JSTL? What features does it offer?

JSTL design principles JSTL 1. 0: Keep it simple! ¢ Targeted tags ¢ l JSTL design principles JSTL 1. 0: Keep it simple! ¢ Targeted tags ¢ l Could have a single tag: • 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 The parable of Mike and Phillipe Mike Credit: Pierre Delisle (spec lead) Phillipe

JSTL 1. 0 features ¢ ¢ ¢ Control flow l Iteration, conditions URL management 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) 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}” /> JSTL features: managing variables ¢ Outputting values with EL ¢ Storing data // arbitrary text Note the use of “var” and “scope”: a JSTL convention

JSTL features: iteration ¢ Iteration <c: for. Each items=”${list}” begin=” 5” end=” 20” step=” JSTL features: iteration ¢ Iteration ¢ “paging”

JSTL features: conditional logic ¢ Conditional evaluation <c: if test=”${a == b}”> a equals JSTL features: conditional logic ¢ Conditional evaluation a equals b ¢ Mutually exclusive conditionals a equals b a equals c I don’t know what ’a’ equals.

JSTL features: URL management ¢ Retrieving data <c: import var=”cnn” url=”http: //www. cnn. com/cnn. JSTL features: URL management ¢ Retrieving data 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 ¢ Redirection

JSTL features: text formatting ¢ Locale-sensitive formatting and parsing l l ¢ <fmt: format. JSTL features: text formatting ¢ Locale-sensitive formatting and parsing l l ¢ Internationalization l ¢ Numbers Dates Message bundles 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 JSTL features: XML manipulation ¢ Use of XPath to access, display pieces of XML documents ¢ Chaining XSLT transformations

Advantages of JSTL XML/XPath support ¢ Why not always use XSLT? l JSTL integrates 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 features: database manipulation ¢ Queries (and Result. Set caching) <sql: query sql=“SELECT * JSTL features: database manipulation ¢ Queries (and Result. Set caching) ¢ ¢ Updates / inserts Transactions () Parametric (Prepared. Statement) argument substitution () Data. Source-based connection management

SQL tags: the debate Tag library Database JSP page Back-end Java code Tag library 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 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 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 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? Question 4 ¢ How do the technologies work together?

“Models” of JSP development ¢ Origin of the terms “model 1” and “model 2. “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 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 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: ${d. property 1} • 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: Transferring data Use XML documents (i. e. , DOM objects) and the JSTL 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 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: 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: shawn. bayern@yale. edu

Q&A ¢ Syntax? Semantics? Other features? ¢ Java Community Process procedures, anecdotes? ¢ Future Q&A ¢ Syntax? Semantics? Other features? ¢ Java Community Process procedures, anecdotes? ¢ Future directions?