Implementing jsp tag extensions

Post on 20-Jan-2017

89 views 2 download

Transcript of Implementing jsp tag extensions

{

Implementing JSP Tag

Extensions

CUSTOM TAGS User Defined tags

Reduce the use of scripting elements in a JSP page

Allows to create new and reusable tags

Can use in any JSP page with the help of tag libraries

A Tag library provides the capability to define new customized tags

Major features of custom tags: Reusability Readability Maintainability Portabiltity

Exploring the Elements of Tag Extensions

The TLD file The tag handler The taglib directive

Basic elements of Custom tags

XML document describing tag library

Provides documentation of tag library and version information of JSP container

Contains the name of TagLibraryValidator class

The TLD file

Used to implement the functionality of a custom tag

To set a custom tag in a JSP page,<%@ taglib prefix=“p” uri=“Mytld.tld”

%>

Features: Declares that a tag library is used Identifies the location of the tag library Associates a tag prefix with the usage of

actions in the library

The taglib directive

Java class where a custom tag is defined

Can define tag handlers by implementing interfaces or by extending an abstract base class from javax.servlet.jsp.tagext package

Various tag handler interfaces are Tag, BodyTag, IterationTag and SimpleTag

JSP technology defines 2 types of tag handlers: Classic tag handler Simple tag handler

The Tag handler

Exploring the Tag Extension API

The tag extension API provides the javax.servlet.jsp.tagext package.

Contains various classes and interfaces

Similar to HTML/XML tags

Terms associated with the implementation of a tag extension Tag name-combination of prefix and suffix,separated

by a colon. For example :- <jsp:forward />tag Attributes-refers to a value that is assigned to an

attribute of a tag.

Nesting-process in which a tag is used within another.

For example, <jsp:param />tag is used within <jsp:include /> and <jsp:forward />tags

Body content-refers to content,such as expressions and scriplets.

The tag Extension Interfaces

§ The Tag interface§ The JspTag interface § The IterationTag interface§ The BodyTag interface§ The DynamicAttributes interface§ The SimpleTag interface§ The TryCatchFinally interface§ The JspIdConsumer interface

1. The Tag interface

Basic protocol between tag handler and a JSP page.

dostartTag() and doEndTag() setParent(tag t) getParent() release()

Describing the Fields of the Tag interfaces

EVAL_BODY_INCLUDE EVAL_PAGE SKIP_BODY SKIP_PAGE

2. The JspTag Interface Serves as a base interface for the Tag and

SimpleTag interface.

Used for organizational and type-safety purposes.

BodyTag,IterationTag,SimpleTag and Tag -interfaces are sub-interfaces.

3. The IterationTag interface Build tag handlers that repeatedly re-evaluate the body of a

custom tag. Extends the Tag interface.

Method: doAfterBody()

Fields: EVAL_BODY_AGAIN-Re-evaluates the body content. SKIP_BODY-stops the evaluation of the body content.

4. The BodyTag Interface Extends the Iteration Tag interface.

Methods:doInitBody() - evaluates the body of a custom tag

before initializing it,not invoked for empty tag.

setBodyContent(BodyContent b)-sets the body content of the custom tag.

5. The DynamicAttributes interface To provide support for dynamic attributes.

SetDynamicAttribute() avoids the translation- time errors.

JspException exception is thrown.

6. The simpleTag Interface Created by implementing the SimpleTag interface.

Methods:

doTag() - evaluating and iterating the body content of a tag.

getParent() - returns the parent of the custom tag. setJspBody - provides the body of the custom tag as

a JspFragment object.

7. The TryCatchFinally Interface To handle the exceptions that may occur within the tag

handler class. doStartTag() and doEndTag() may throw JspException.

Methods:doCatch()-invoked whenever there an exception arises

during the evaluation of the body of the current tag.doFinally()-gets invoked after the processing of the doEndTag() method is complete.

8. The JspIdConsumer Interface Jsp container should provide a compiler generated id .

JspId attribute is a string value,similar to <jsp:id>tag

Difference is <jsp:id> is evaluated at the execution time.

provides single method,setJspId(string id)

Unique id during translation process.

The Tag Extension Classes

The TagSupport Class

Is an abstract class that implements the tag as well as IterationTag interfaces and provides support for all the methods.

Static method Methods:

doAfterBody()-body content of the tag after the invocation of the doStartTag()

doEndTag()-returns EVAL_PAGE field,by default,on executing the end tag.

doStartTag()-SKIP_BODY field after the execution of the start tag.

getValue()- returnsng string value.

getId()-returns values of the id attribute/null value

getValues()-get the corresponding values

removeValue(java.lang.string k)-removes the string value.

setId(java.lang.string Id)-Sets the id attribute. setPageContext()-Sets the page context.

Fields

Id-specifies a String value for a tag PageContext-provides access to al the namespaces and

page attributes.

The BodyContent Class

Is a subclass of the JspWriter class and encapsulates the evaluation of the body of an action.

pushBody() or popBody()-creates instances of the BodyContent class

Methods:

getReader()-Returns the value of the BodyContent object as a Reader object.

getString()-as a string writeOut(java.io.Writer out)-writes the content of the

BodyContent object into a writer object. getEnclosingWriter()-enclosing JspWriter object. clearBody()-clrs the body of the buffer.

The BodyTagSupport Class

Implements the BodyTag interface .

Acts as a base class to create tag handlers without defining each method of the BodyTag interface

8.11

The FunctionInfo Class

Provides information abt a function defined in the tag library.

Instantiated from the TLD file.

Available only at the time of translation of a JSP page.

Methods

getFunctionClass() - Returns the class of a function. getFunctionSignature() - signature. getName - Name

The JspFragment class

Encapsulates the jsp code in an object that can be invoked multiple times.

Manually either by page author or by TLD file. Methods: getJspContext()-returns the JspContext object that is used

by the current JspFragment object. Invoke(java.io.Writer out)-Executes the JspFragment

object.

The SimpleTagSupport Class

Implements the SimpleTag interface

Provides the defination for all the implemented methods of the SimpleTag interface.

Methods: doTag() -processes a simple tag handler.

getJspBody() -returns a fragment that encapsulates the body passed by the container.

getJspContext()-returns the page context.

getParent()-parent tag of a simple tag.

setJspBody(JspFragment jspBody)-stores the specified JspFragment object.

setJspContext(JspContext pc)-stores the provided JSP context in the private JspContext.

setParent(JspTag parent)-sets the parent tag of the simple tag.

The TagAdapter class

Allows the collaboration bw classic tag handlers and simple tag handlers.

Methods:

getAdaptee()-instance of simple tag handler that is being adapted to the tag interface.

getParent()-returns the parent of the simple tag.

The TaglibraryInfo class

Provides translation-time information associated with a taglib directive and TLD.

8.16

8.17

The TagInfo Class

Provides information of a specific tag provided in a tag library.

Instance of TLD.

8.18

8.19

The TagFileInfo Class

Provides information about a tag file in a tag library.

TLD instantiates,available only at translation time.

Code Snippet

TagFileInfo(name, path, Taginfo)

Methods:

getName()-returns a unique action name of the tag.

getPath()-path to locate the .tagfile.

getTagInfo()object containing the information abt the tag.

The TagAttributeInfo Class

Contains information abt tag attributes.

ID as its attribute.

Specifies a string value for a custom tag.

The TagExtraInfo Class

Provides a mechanism to validate custom tags using tag attributes in TLD.

The <attribute>tag contains a set of three tags,name> ,<required> and<rtexprvalue>

Low level validation mechanism.

Methods:

getTagInfo()-returns TagInfo object of the custom tag.

getVariableInfo(Tagdata data)-a zero length array,if no scripting variables are defined.

isValid(Tagdata data)-instance is valid.

setTagInfo(Taginfo tagInfo)-sets the specied TagInfo for the custom tag handler.

The PageData Class

Provides the translation-time information on a JSP page.

Provides a single method i,e getInputStream().

Returns an input stream of a JSP page in the form of XML and stream encoding is done in UTF-8

The VariableInfo Class

Determines the type of the scripting variables that are created or modified by a tag at runtime

Class should be provided in the classpath of the web application.

The TagData Class

Object of TD is used as an argument in the Validate(), isValid(),getVariableInfo() methods of the TagExtraInfo class at the translation time.

The TagLibraryValidator Class

Validates a JSP page during the translation time. Validate(String prefix,String uri,PageData page) First two parameters are used to indicate how a tag

library is mapped in the jsp page. Last parameter is used to represent the XML view of the

page being validated.

The ValidationMessage Class

Is a piece of information that is provided by either the TagLibraryValidator or the TagExtraInfo object.

JSP container can also use this VM obj to retrieve information abt the location of errors.

Methods: getId()-returns <jsp:id> attribute. getMessage()-localized validation message.

Java class that implements the Tag, IterationTag or BodyTag interface

Working with Classic Tag Handlers

Steps to develop the ClassicTag application: Creating the Tag handler for ClassicTag

application Creating TLD for ClassicTag application Creating html file for ClassicTag

application Creating JSP file for ClassicTag

application Configuring web.xml file for ClassicTag

application Defining the directory structure of

ClassicTag application Packaging, running and deploying the

ClassicTag application

Implementing Classic Tags

CustomMessage.javapackage com.kogent.tags;import javax.servlet.ServletRequest;import javax.servlet.jsp.tagext.*;

public class CustomMessage extends BodyTagSupport

{

String pname;private static final long serialVersionUID = 1L;public void setParamName(String s){

pname=s;}

public String getParamName(){

return pname;}public int doStartTag() {

ServletRequest req=pageContext.getRequest();

String pvalue=req.getParameter(pname);if ((pvalue.equals("japan")) || (pvalue.equals("Japan"))) {

return EVAL_BODY_INCLUDE;}

else {

return SKIP_BODY;}

} //doStartTag//doStartTag

public int doAfterBody(){

return SKIP_BODY;}//doAfterBodypublic int doEndTag(){

return EVAL_PAGE;}//doEndTag

}

CustomTags.tld<?xml version="1.0" ?><jsp-version>2.1</jsp-version> <tlib-version>1.1</tlib-version> <short-name>tag</short-name> <tag> <name>check</name> <tag-class>com.kogent.tags.CustomMessage</tag-class> <body-content>JSP</body-content> <attribute> <name>check</name> <required>true</required> <rtexprvalue>false</rtexprvalue> </attribute> </tag></taglib>

<html><body><form action="TestPage.jsp"><b> PREDICT AND WIN !!! </b><BR/><BR/> <p style="color:blue">The country which is known as "land of rising sun" </p> <input type="text" name="opt"/> <input type="submit" value="check"/></form></body></html>

Home.html

<%@taglib uri="/WEB-INF/CustomTags.tld" prefix="tag"%><html> <body> <tag:check paramName = "opt"> <b>congratulations you have won a prize!!!</b> </tag:check></body></html>

TestPage.jsp

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <welcome-file-list> <welcome-file>home.html</welcome-file> </welcome-file-list></web-app>

Web.xml

Displaying the Directory structure of Classic tag application

Output

Java class that implements the SimpleTag interface

The javax.servlet.jsp.tagext.SimpleTagSupport class provides default implementation of all methods in simple tags

Working with Simple Tag Handlers

Steps to develop the SimpleTag application:

Creating the Tag handler for SimpleTag application

Creating TLD for SimpleTag application Creating JSP file for SimpleTag application Configuring web.xml file for SimpleTag

application Defining the directory structure of

SimpleTag application Packaging, running and deploying the

SimpleTag application

Implementing Simple Tags

package com.kogen.tags;import javax.servlet.jsp.tagext.*;import javax.servlet.jsp.*;import java.io.*;import java.util.Date;public class CustomMessage1 extends SimpleTagSupport{

public void doTag() throws JspException,IOException {JspContext context=getJspContext();JspWriter Out=context.getOut();Out.println("Welcome!!! You are visting this Web page on"+new

Date());}

}

CustomMessage1.java

<?xml version="1.0" ?><taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_ 1.xsd"> <jsp-version>2.1</jsp-version> <tlib-version>1.1</tlib-version> <short-name>tag</short-name> <tag> <name>CustomMessage1</name> <tag-class>com.kogent.tags.CustomMessage1</tag-class> <body-content>empty</body-content> </tag></taglib>

CustomTags.tld

<%@ taglib uri="/WEB-INF/CustomTags.tld" prefix="tag"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><link rel="stylesheet" type="text/css" href="mystyle.css"></head><body><tag:CustomMessage1/><br></body></html>

test.jsp

<?xml version="1.0" encoding="UTF-8"?><web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <welcome-file-list> <welcome-file>test.jsp</welcome-file> </welcome-file-list></web-app>

Web.xml

Displaying the Directory structure of Simple tag application

Output:

1. What are the major features of custom tags?2. What are the 3 basic elements of custom tags?3. What is TLD file?4. Tell me any 1 feature of taglib directive.

………..?

Thank you