Www.coreservlets.com Custom Tags1 Usage Rules PowerPoint slides for use only in for-credit courses at degree-granting institutions Slides can be modified.

Slides:



Advertisements
Similar presentations
Enterprise Java: Developing JSP Custom Tag Libraries Developing JSP Custom Tag Libraries O'Reilly Conference on Enterprise Java, March 2001.
Advertisements

9 Copyright © 2005, Oracle. All rights reserved. Modularizing JavaServer Pages Development with Tags.
JSP and web applications
Creating Custom JSP Tag Libraries Taken from Core Servlets and JavaServer Pages from Prentice.
CS4273: Distributed System Technologies and Programming I Lecture 11: JavaServer Pages (JSP)
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
© Yaron Kanza Advanced Java Server Pages Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher.
Java II--Copyright © Tom Hunter. J2EE JSP Custom Tag Libraries.
Advanced Java Server Pages An more detailed look at JSPs.
JSP Tag Extensions And Java Bean. JSP Tag Extensions Tag extensions look like HTML (or rather, XML) tags embedded in a JSP page. They have a special meaning.
DT211/3 Internet Application Development
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
Generate Dynamic Content On Cache Server Master’s Project Proposal by Aparna Yeddula.
JSP Java Server Pages Reference:
DT228/3 Web Development JSP: Directives and Scripting elements.
Object-Oriented Enterprise Application Development JavaServer Pages Tag Libraries.
11. Java-Based Web: JSP, JSF. 2 Motto: Rule 1: Our client is always right Rule 2: If you think our client is wrong, see Rule 1. - Anonymous.
1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 9 JavaServer Pages (JSP) (Based on Møller.
Java Server Pages CS-422. What are JSPs A logical evolution of java servlets –most servlets dynamically create HTML and integrate it with some computational.
Java for the WWW November 2012Slide Tag Libraries What are they? –Custom libraries Custom tags – see examples in following slides.
OOSSE - OO Review Review session A review of other OO technologies and may be useful for exam (not required for assignment) OO web development philosophy.
Basic Elements JSP For a Tutorial, see:
CSC 2720 Building Web Applications Using Java Beans, Custom Tags and Tag Libraries in JSP pages.
Slides © Marty Hall, book © Sun Microsystems Press 1 Including Files & Applets in JSP Documents Core Servlets & JSP book:
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
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.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
® IBM Software Group © 2007 IBM Corporation JSP Custom Tags
1 JSP 1.2 Custom Tags. 2 Agenda ● What is and why custom tags? ● Components that make up custom tag architecture ● How to create custom tags? ● How does.
Chapter 7 Java Server Pages. Objectives Explain how the separation of concerns principle applies to JSP Describe the operation and life-cycle of a JSP.
Introduction to JavaServer Pages (JSP) Slides from Dr. Mark Llewellyn.
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,
Getting Started with HTML Please use speaker notes for additional information!
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.
Slides © Marty Hall, book © Sun Microsystems Press 1 JSP Scripting Elements Core Servlets & JSP book:
1 JSP with Custom Tags Blake Adams Introduction Advanced Java Server Pages – Custom Tags Keyterms: - Tag Library Descriptor(TLD) - Tag Libraries.
JSTL Lec Umair©2006, All rights reserved JSTL (ni) Acronym of  JavaServer Pages Standard Tag Library JSTL (like JSP) is a specification, not an.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
Fall 2007cs4201 Advanced Java Programming Umar Kalim Dept. of Communication Systems Engineering
COMP 321 Week 11. Overview Lab 8-1 Solution Tag Files Custom Tags Web Application Deployment.
Chapter 7 Using Custom Tag Libraries and the JSP Standard Tag Library.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
JSP Tag Libraries Lec Last Lecture Example We incorporated JavaBeans in “Course Outline” Example But still have to write java code inside java.jsp.
Java server pages. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. A JSP file basically contains.
JSP Custom Tags. Prerequisites Servlet API Mapping to JSP implicit objects JavaServer Pages Basic syntax Implementation via servlet API XML.
CSC 2720 Building Web Applications JavaServer Pages (JSP) JSP Directives and Action Elements.
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. Types of JSP Scripting Elements Expressions of the form, which are evaluated and inserted into the servlet's output. Scriptlets of the form, which.
Slides © Marty Hall, book © Sun Microsystems Press 1 Using JavaBeans with JSP Core Servlets & JSP book:
JSP BASICS AND ARCHITECTURE. Goals of JSP Simplify Creation of dynamic pages. Separate Dynamic and Static content.
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.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Java Web 应用开发: J2EE 和 Tomcat 蔡 剑, Ph.D.. 本讲内容 Web 层技术 (III) Custom Tags JSP and XML JSTL.
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.
SKT-SSU IT Training Center Servlet and JSP. Chapter Eleven: Invoking Java Code with JSP Scripting Elements.
Java Server Pages. Servlets are nice, but… –It’s a pain to put in all those out.println stmts JSPs mix Java and HTML –Within the same document Nice for.
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.
Chapter 14 Using JavaBeans Components in JSP Documents.
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.
J2EE JSP Custom Tag Libraries 1 3 JSP: Custom Tag Libraries.
JSP Java Server Pages. Hello, !
JSP: Actions elements and JSTL
Knowledge Byte In this section, you will learn about:
Pre-assessment Questions
Presentation transcript:

Custom Tags1 Usage Rules PowerPoint slides for use only in for-credit courses at degree-granting institutions Slides can be modified however instructor desires Instructor can give PDF or hardcopy to students, but should protect the PowerPoint files –This slide is suppressed in Slide Show mode

Slides © Marty Hall, book © Sun Microsystems Press 2 Creating Custom JSP Tag Libraries Core Servlets & JSP book: More Servlets & JSP book: Servlet and JSP Training Courses: courses.coreservlets.com

Custom Tags3 Agenda Components of a tag library Basic tags Tags that use attributes Tags that use body content Tags that optionally use body content Advanced tags

Custom Tags4 Uses of JSP Constructs Scripting elements calling servlet code directly Scripting elements calling servlet code indirectly (by means of utility classes) Beans Custom tags Servlet/JSP combo (MVC), with beans and possibly custom tags Simple Application Complex Application

Custom Tags5 Components That Make Up a Tag Library The Tag Handler Class –Java code that says how to actually translate tag into code –Must implement javax.servlet.jsp.tagext.Tag interface –Usually extends TagSupport or BodyTagSupport –Goes in same directories as servlet class files and beans The Tag Library Descriptor File –XML file describing tag name, attributes, and implementing tag handler class –Goes with JSP file or at arbitrary URL The JSP File –Imports a tag library (referencing URL of descriptor file) –Defines tag prefix –Uses tags

Custom Tags6 Defining a Simple Tag Handler Class: Example package coreservlets.tags; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import java.io.*; import java.math.*; import coreservlets.*; public class SimplePrimeTag extends TagSupport { protected int len = 50; public int doStartTag() { try { JspWriter out = pageContext.getOut(); BigInteger prime = Primes.nextPrime(Primes.random(len)); out.print(prime); // Primes class defined in Section 7.3 } catch(IOException ioe) { System.out.println("Error generating prime: " + ioe); } return(SKIP_BODY); }}

Custom Tags7 Defining a Simple Tag Library Descriptor Start with XML header and DOCTYPE Top-level element is taglib Each tag defined by tag element with: –name, whose body defines the base tag name. In this case, I use simplePrime –tagclass, which gives the fully qualified class name of the tag handler. In this case, I use coreservlets.tags.SimplePrimeTag –bodycontent, which gives hints to development environments. Optional. –info, which gives a short description. Here, I use Outputs a random 50-digit prime.

Custom Tags8 TLD File for SimplePrimeTag <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" " // A few standard items -- just copy these simplePrime coreservlets.tags.SimplePrimeTag Outputs a random 50-digit prime. Don't memorize XML header and DOCTYPE; modify version from coreservlets.com

Custom Tags9 Accessing Custom Tags From JSP Files Import the tag library –Specify location of TLD file –Define a tag prefix (namespace) Use the tags – Tag name comes from TLD file Prefix comes from taglib directive –E.g.,

Custom Tags10 Using simplePrime Tag... Some 50-Digit Primes

Custom Tags11 Using simplePrime Tag: Result

Custom Tags12 Assigning Attributes to Tags Allowing tags like – Tags are still standalone –No body between start and end tags

Custom Tags13 Attributes: The Tag Handler Class Use of an attribute called attribute1 simply results in a call to a method called setAttribute1 –Attribute value is supplied to method as a String Example –To support add the following to tag handler class: public void setAttribute1(String value1) { doSomethingWith(value1); }

Custom Tags14 Attributes: PrimeTag.java package coreservlets.tags; public class PrimeTag extends SimplePrimeTag { public void setLength(String length) { try { // len used by parent class len = Integer.parseInt(length); } catch(NumberFormatException nfe) { len = 50; }

Custom Tags15 PrimeTag (Continued) public void release() { len = 50; } Why release ? –Servers are permitted to reuse tag instances No synchronization issues, since reuse occurs only after tag processing is totally finished. –Few current servers reuse tags, but you should plan ahead –Not needed if attribute is required. (Why not?)

Custom Tags16 Attributes: The Tag Library Descriptor File The tag element must contain a nested attribute element The attribute element has three further- nested elements –name, a required element that defines the case-sensitive attribute name. In this case, I use length –required, a required element that stipulates whether the attribute must always be supplied (true) or is optional (false). Here, to indicate that length is optional, I use false –rtexprvalue, an optional attribute that indicates whether the attribute value can be a JSP expression like (true) or whether it must be a fixed string (false). The default value is false.

Custom Tags17 TLD File for PrimeTag... prime coreservlets.tags.PrimeTag Outputs a random N-digit prime. length false

Custom Tags18 Using prime Tag... Some N-Digit Primes 20-digit: 40-digit: 80-digit: Default (50-digit):

Custom Tags19 Using prime Tag: Result

Custom Tags20 Including the Tag Body Simplest tags – Tags with attributes – Now – JSP Content

Custom Tags21 Using Tag Body: The Tag Handler Class doStartTag –Usually returns EVAL_BODY_INCLUDE instead of SKIP_BODY doEndTag –Define this method if you want to take action after handling the body –Return EVAL_PAGE

Custom Tags22 Using Tag Body: HeadingTag.java package coreservlets.tags; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import java.io.*; public class HeadingTag extends TagSupport { private String bgColor; // The one required attribute private String color = null;... public void setBgColor(String bgColor) { this.bgColor = bgColor; } public void setColor(String color) { this.color = color; }...

Custom Tags23 Using Tag Body: HeadingTag.java (Continued) public int doStartTag() { try { JspWriter out = pageContext.getOut(); out.print("<TABLE BORDER=" + border + " BGCOLOR=\"" + bgColor + "\"" + " ALIGN=\"" + align + "\""); if (width != null) { out.print(" WIDTH=\"" + width + "\""); }... } catch(IOException ioe) { System.out.println("Error in HeadingTag: " + ioe); } return(EVAL_BODY_INCLUDE); // Include tag body }

Custom Tags24 Using Tag Body: HeadingTag.java (cont) public int doEndTag() { try { JspWriter out = pageContext.getOut(); out.print(" "); } catch(IOException ioe) { System.out.println("Error in HeadingTag: " + ioe); } return(EVAL_PAGE); // Continue with rest of JSP page }

Custom Tags25 Using Tag Body: The Tag Library Descriptor File Only difference is bodycontent element –Should be JSP instead of empty: … … JSP … Purpose is primarily for development environments –Advanced IDEs may have drag-and-drop support for custom tags –Defined as optional in JSP specification I will omit in my examples

Custom Tags26 TLD File for HeadingTag... heading coreservlets.tags.HeadingTag Outputs a 1-cell table used as a heading. bgColor true color false...

Custom Tags27 Using heading Tag Default Heading White on Black Heading Large Bordered Heading Heading with Full-Width Background...

Custom Tags28 Using heading Tag: Result

Custom Tags29 Optional Tag Bodies First examples had no tag bodies –doStartTag returned SKIP_BODY Most recent examples always included tag bodies –doStartTag returned EVAL_BODY_INCLUDE Now: decide whether or not to include tag body at request time –Have doStartTag return either SKIP_BODY or EVAL_BODY_INCLUDE depending on values of request time information

Custom Tags30 Optional Tag Bodies: DebugTag.java package coreservlets.tags; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import java.io.*; import javax.servlet.*; public class DebugTag extends TagSupport { public int doStartTag() { ServletRequest request = pageContext.getRequest(); String debugFlag = request.getParameter("debug"); if ((debugFlag != null) && (!debugFlag.equalsIgnoreCase("false"))) { return(EVAL_BODY_INCLUDE); } else { return(SKIP_BODY); } }}

Custom Tags31 TLD File for DebugTag... debug coreservlets.tags.DebugTag Includes body only if debug param is set.

Custom Tags32 Using debug Tag Top of regular page. Blah, blah, blah. Yadda, yadda, yadda. Debug: Current time: Requesting hostname: Session ID: Bottom of regular page. Blah, blah, blah. Yadda, yadda, yadda.

Custom Tags33 Using debug Tag: Results

Custom Tags34 Manipulating the Tag Body No tag body – Previous uses of tag body – JSP Content –Content inserted verbatim Now –Same JSP syntax for using a tag body –Java code can read/modify/replace tag body

Custom Tags35 Manipulating Tag Body: The Tag Handler Class Extend BodyTagSupport –TagSupport does not have enough infrastructure to support reading/manipulating the tag body New method to override: doAfterBody –Return SKIP_BODY when done getBodyContent returns object of type BodyContent that has three key methods –getEnclosingWriter -- returns the JspWriter being used by doStartTag and doEndTag –getReader -- returns a Reader that can read tag’s body –getString -- returns a String containing entire tag body

Custom Tags36 Manipulating Tag Body: FilterTag.java public class FilterTag extends BodyTagSupport { public int doAfterBody() { BodyContent body = getBodyContent(); String filteredBody = // The filter method is defined in Section 3.6 ServletUtilities.filter(body.getString()); try { JspWriter out = body.getEnclosingWriter(); out.print(filteredBody); } catch(IOException ioe) { System.out.println("Error in FilterTag: " + ioe); } // SKIP_BODY means I'm done. If I wanted to evaluate // and handle body again, I'd return EVAL_BODY_TAG. return(SKIP_BODY); }

Custom Tags37 Manipulating Tag Body: The Tag Library Descriptor File No new capabilities needed filter coreservlets.tags.FilterTag Replaces HTML-specific characters in body.

Custom Tags38 Using the filter Tag... Example Result Some emphasized text. Some strongly emphasized text. Some code.... Some emphasized text. Some strongly emphasized text. Some code....

Custom Tags39 Using the filter Tag: Results

Custom Tags40 Advanced Custom Tags Manipulating the body multiple times –Return EVAL_BODY_TAG from doAfterBody until last repetition –Use the TLD file to specify that JSP expressions are permitted as attribute values Nested tags –The handler for the inner tag uses findAncestorWithClass to get a reference to the enclosing tag handler Details and examples of both are given in the book

Custom Tags41 Manipulating the Body Multiple Times: the repeat Tag <!-- Repeats N times. A null reps value means repeat once. --> <csajsp:repeat reps=' '>

Custom Tags42 Using the repeat Tag: Results

Custom Tags43 Nested Tags: the if Tag true Condition was true Condition was false... Some coin tosses: 0.5 %> Heads Tails

Custom Tags44 Using the if Tag: Results

Custom Tags45 Open Source Tag Libraries JSP Standard Tag Library (JSTL) –See Internationalization (I18N) Database access Sending JNDI Date/time Populating/validating form fields Perl regular expressions Extracting data from other Web pages XSL transformations Etc.

Custom Tags46 Summary For each custom tag, you need –A tag handler class (usually extending TagSupport or BodyTagSupport) –An entry in a Tag Library Descriptor file –A JSP file that imports it, specifies prefix, and uses it Simple tags –Generate output in doStartTag, return SKIP_BODY Attributes –Define setAttributeName method. Update TLD file Body content –doStartTag returns EVAL_BODY_INCLUDE –Add doEndTag method

Slides © Marty Hall, book © Sun Microsystems Press 47 Questions? Core Servlets & JSP book: More Servlets & JSP book: Servlet and JSP Training Courses: courses.coreservlets.com

Custom Tags48 More Information Source code for all examples – Servlet/JSP Training Courses – Core Servlets & JSP – More Servlets & JSP –Sequel to Core Servlets & JSP – Servlet home page – JavaServer Pages home page –