Using JSP 2.0’s New Features Shawn Bayern Research Programmer, Yale University JSTL reference-implementation lead Author, JSTL in Action Web Development.

Slides:



Advertisements
Similar presentations
9 Copyright © 2005, Oracle. All rights reserved. Modularizing JavaServer Pages Development with Tags.
Advertisements

Apache Struts Technology
JSP1 Java Server Pages (JSP) Introducing JavaServer Pages TM (JSP TM ) JSP scripting elements.
Expression Language Lec Umair Javed©2006 Generating Dynamic Contents Technologies available  Servlets  JSP  JavaBeans  Custom Tags  Expression.
Using JavaServer Pages Harry R. Erwin, PhD CIT304/CSE301.
JSTL and Web Development at Universities Shawn Bayern Research programmer, Yale University JSTL reference-implementation lead Author, Web Development with.
WEB1P servintro1 Introduction to servlets and JSP Dr Jim Briggs.
DT211/3 Internet Application Development
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
JSP Java Server Pages Reference:
JSP 2.0 and JSTL: Principles and Patterns Shawn Bayern Research Programmer, Yale University JSTL reference-implementation lead Author, JSTL in Action Web.
DT228/3 Web Development JSP: Directives and Scripting elements.
Apache Struts Technology A MVC Framework for Java Web Applications.
JSP Architecture  JSP is a simple text file consisting of HTML or XML content along with JSP elements  JSP packages define the interface for the compiled.
Introduction to Java web programming Dr Jim Briggs JWP intro1.
Struts 2.0 an Overview ( )
UNIT-V The MVC architecture and Struts Framework.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
Overview of JSP Technology. The need of JSP With servlets, it is easy to – Read form data – Read HTTP request headers – Set HTTP status codes and response.
1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 9 JavaServer Pages (JSP) (Based on Møller.
Netbeans – jsp.zip Introduction to JSP Netbeans – jsp.zip.
JSP Standard Tag Library
SDPL 2002Notes 7: Apache Cocoon1 7 XML Web Site Architecture Example: Apache Cocoon, a Web publishing architecture based on XML technology
CSC 2720 Building Web Applications Using Java Beans, Custom Tags and Tag Libraries in JSP pages.
Using JavaBeans and Custom Tags in JSP Lesson 3B / Slide 1 of 37 J2EE Web Components Pre-assessment Questions 1.The _____________ attribute of a JSP page.
® IBM Software Group © 2007 IBM Corporation JSP Custom Tags
Introduction to Java Server Pages (JSPs) Robert Thornton.
Java Server Pages A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format,
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
Organization of the platform Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages.
JAVA SERVER PAGES. 2 SERVLETS The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
Stanisław Osiński, 2002JSP – A technology for serving dynamic web content Java Server Pages™ A technology for serving dynamic web content Stanisław Osiński,
JAVA SERVER PAGES CREATING DYNAMIC WEB PAGES USING JAVA James Faeldon CS 119 Enterprise Systems Programming.
Fall CIS 764 Database Systems Design L8. Web ….
JSTL, XML and XSLT An introduction to JSP Standard Tag Library and XML/XSLT transformation for Web layout.
JSTL Lec Umair©2006, All rights reserved JSTL (ni) Acronym of  JavaServer Pages Standard Tag Library JSTL (like JSP) is a specification, not an.
Fall 2007cs4201 Advanced Java Programming Umar Kalim Dept. of Communication Systems Engineering
Introduction to JavaServer Pages. 2 JSP and Servlet Limitations of servlet  It’s inaccessible to non-programmers JSP is a complement to servlet  focuses.
CSC 2720 Building Web Applications JavaServer Pages (JSP) The Basics.
JSP Tag Libraries Lec Last Lecture Example We incorporated JavaBeans in “Course Outline” Example But still have to write java code inside java.jsp.
Copyright © 2002 ProsoftTraining. All rights reserved. JavaServer Pages.
JSTL The JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which encapsulates core functionality common to many JSP applications.
CS320 Web and Internet Programming Custom Tag Library Chengyu Sun California State University, Los Angeles.
JavaServer Page by Antonio Ko. Overview ► Introduction ► What is a servlet? ► What can servlets do? ► Servlets Vs JSP ► Syntax ► Samples ► JavaBean ►
JSP Custom Tags. Prerequisites Servlet API Mapping to JSP implicit objects JavaServer Pages Basic syntax Implementation via servlet API XML.
JSP Pages. What and Why of JSP? JSP = Java code imbedded in HTML or XML –Static portion of the page is HTML –Dynamic portion is Java Easy way to develop.
JSP BASICS AND ARCHITECTURE. Goals of JSP Simplify Creation of dynamic pages. Separate Dynamic and Static content.
CS562 Advanced Java and Internet Application Introduction to the Computer Warehouse Web Application. Java Server Pages (JSP) Technology. By Team Alpha.
JAVA BEANS JSP - Standard Tag Library (JSTL) JAVA Enterprise Edition.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
Basic JSP Celsina Bignoli Problems with Servlets Servlets contain –request processing, –business logic –response generation all lumped.
COMP9321 Web Application Engineering Semester 2, 2015 Dr. Amin Beheshti Service Oriented Computing Group, CSE, UNSW Australia Week 3 1COMP9321, 15s2, Week.
Java Servlets and Java Server Pages
Rich Internet Applications 2. Core JavaScript. The importance of JavaScript Many choices open to the developer for server-side Can choose server technology.
1 Java Server Pages A Java Server Page is a file consisting of HTML or XML markup into which special tags and code blocks are inserted When the page is.
Chapter 6 Chapter 6 Server Side Programming (JSP) Part 1 1 (IS 203) WebProgramming (IS 203) Web Programming.
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
Java Server Pages. 2 Servlets The purpose of a servlet is to create a Web page in response to a client request Servlets are written in Java, with a little.
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
10 Copyright © 2004, Oracle. All rights reserved. Building ADF View Components.
® IBM Software Group © 2007 IBM Corporation JSP Tag Files
Apache Struts Technology A MVC Framework for Java Web Applications.
Lecture Transforming Data: Using Apache Xalan to apply XSLT transformations Marc Dumontier Blueprint Initiative Samuel Lunenfeld Research Institute.
JSP: Actions elements and JSTL
JSP (Java Server Page) JSP is server side technology which is used to create dynamic web pages just like Servlet technology. This is mainly used for implementing.
Java Servlets.
Knowledge Byte In this section, you will learn about:
Design and Maintenance of Web Applications in J2EE
JSP 2.0 and JSTL: Principles and Patterns
JavaServer Faces: The Fundamentals
Presentation transcript:

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

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 book’s title aren’t just words, it’s a methodological principle. The discussion concentrates on practice rather than theory and specifications.” —JavaRanch.com

JSTL in Action “The jokes seem inappropriate.” — Internal reviewer

“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?

Crash course on the J2EE Presentation Tier Your application Java language Java Servlet API JavaServer Pages (JSP) JSTL Your web pages

Crash course on the J2EE Presentation Tier J2EE JSP JSTL Servlets Current standards: JSP 1.2 Servlet 2.3 JSTL 1.0 In a few months: JSP 2.0 Servlet 2.4 JSTL 1.1 JSTL

More details about scheduling JSP 2.0 is currently in Proposed Final Draft (PFD) JSP 2.0 PFD2 (second draft) is planned for January JSP 2.0, JSTL 1.1, Servlet 2.4 released with J2EE 1.4 (probably a few months from now) JSP 1.2 JSTL 1.0 (JSP 2.0 PFD) As of todayA few weeks (JSP 2.0 PFD2) A few months JSP 2.0 JSTL 1.1

What kinds of things go in JSP pages? Scriptlets <% getFoo(request); printFoo(out); String a = ”username”; %> 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 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 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 J2EE and Java technologies (Servlets, EJB)

What’s irritating about JSP? (  ) The tag-extension protocol is too complicated Tag handler  doStartTag()doEndTag() doCatch()doFinally() doInitBody() doAfterBody() release() Too hard for Gosling, even?

What’s irritating about JSP? (  ) Also, tags don’t support certain kinds of code reuse. ”> : out.println(…); for(…) { out.println(…); … } 

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

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 (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 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?

How easy is XPath? //foo=’bar’ hmm bar

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.”string-value

How easy is XPath? //foo=’bar’ hmm bar True!

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

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”)).getAddress () 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 Expressions may also refer to cookies, request parameters, and other data: ${cookie.colorPreference} ${param.password} ${header[“User-Agent”]} ${pageContext.request.remoteUser} ${initParam.databasePassword}

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

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)

Registering an EL function... isNejugMember org.nejug.Util Boolean isNejugMember(String) public static Boolean isNejugMember(String x);

Using an EL function ${myLib:isNejugMember(user)} <myLib:printStatus member=”${isNejugMember(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: JavaServer Faces; open- source 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 directive instead of traditional directive.

The role of tag files JSP Page.jsp Servlet JSP tag file.tag Tag-handler class

JSP 2.0 tag files Name IQ ${i.fullName} ${i.IQ}

Using the new tag… Your shopping cart: Your wish list: Things we want you to buy:

Tag-file directives Just as boring as Primarily for bookkeeping, tool support E.g., description, large-icon, small-icon isScriptingEnabled isELEnabled

Tag-file directives Declares attributes for the tag you’re creating Provides support for “fragments” Like Dynamo’s “OPARAMS” (ATG) …

Using fragments …

Old tag handler Tag handler  doStartTag()doEndTag() doCatch()doFinally() Tag attributes Tag body doInitBody() doAfterBody() release()

SimpleTag handler Tag handler Tag attributes Tag body (no scriptlets) doTag()

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}; }

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.

JSP 2.0: Improved XML syntax Old style: JSP as document New style: JSP as namespace xmlns:jsp=“

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

JSTL design principles JSTL 1.0 / 1.1: Keep it simple! Targeted tags Could have a single tag: 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 Mike Phillipe Credit: Pierre Delisle (spec lead)

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 Library featuresRecommended prefix Core (control flow, URLs, variable access) c Text formattingfmt XML manipulationx Database accesssql

JSTL features: managing variables Outputting values with EL Storing data <c:set var=”user” scope=”session”> // arbitrary text Note the use of “var” and “scope”: a JSTL convention

JSTL features: iteration Iteration <c:forEach items=”${list}” begin=”5” end=”20” step=”4” var=”item”> “ paging ”

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=” ”/> 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 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}.”

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? 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 vs. XSLT example

JSTL features: database manipulation Queries (and ResultSet caching) Updates / inserts Transactions ( ) Parametric ( PreparedStatement ) argument substitution ( ) DataSource-based connection management …

SQL tags: the debate Tag library JSP page Back-end Java code Database Tag library

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 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 support JSTL API allows registrations of defaults… DataSource Limit on size of results Localization context (Locale, etc.) Time zone

Question 4 How do the technologies work together?

“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 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 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: ${d.property1} 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 tags Use JavaBean-style classes public class MyData { public String getCustomerName() { return X; } public Date getCustomerBirthday() { return Y; } } ${myDataInstance.customerName}

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

URLs 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 address

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