Jsp Custom Tags

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Jsp Custom Tags as PDF for free.

More details

  • Words: 3,167
  • Pages: 81
JSP Custom Tags Outline  Defined  Motivation  Tag Types  Tag Handlers  Tag Library Descriptors  Using Tags in JSPs  Examples

What are Custom Tags? 

A custom tag is a user-defined JSP language element.



JSP custom tags are merely Java classes that implement special interfaces.

What are Custom Tags? 

When a JSP page containing a custom tag is translated into a servlet, the tag is converted to operations on an object called a tag handler. The Web container then invokes those operations when the JSP page's servlet is executed.

Motivation 



Better Packaging By improving the separation between business logic and presentation. Encapsulate common functionality Over a large number of pages and reuse it. This applies to both HTML presentation and application logic.

Motivation 



Reduce number of Scriptlets Scriptlets are not reusable. Eliminate/reduce number of scriptlets in page. Simple to use HTML like syntax, reduces Java code in the page.

Motivation

P r e s e n ta tio n

Im p le m e n ta tio n

HTM L and H T M L - lik e JS P ta g s

Ja v a B e a n s

C u s to m JS P T a g s

What can they do?  Produce content for a JSP page  Access a page’s JavaBeans  Introduce new JavaBeans  Introduce new scripting variables

Tag Types Tags without Body Syntax In HTML

Tags with Body

Syntax In HTML ="anotherValue"> ...tag body...

Tag Types Tags without Body Tags with Body Syntax In JSP Syntax In JSP body

Tag Handler 





A tag handler is an object invoked by the JSP runtime to evaluate a custom tag during the execution of a JSP page that references the tag. The methods of the tag handler are called by the implementation class at various points during the evaluation of the tag. Every tag handler must implement a specialized interface.

javax.servlet.jsp.tagext.Tag  

All tags must implement Tag interface. Defines methods the JSP runtime engine calls to execute a tag.

javax.servlet.jsp.tagext.Tag public interface Tag { public final static int SKIP_BODY = 0; public final static int EVAL_BODY_INCLUDE=1; public final static int SKIP_PAGE = 5; public final static int EVAL_PAGE = 6; void setPageContext(PageContext pageContext); void setParent(Tag parent); Tag getParent(); int doStartTag() throws JspException; int doEndTag() throws JspException; void release(); }

Interface Tag Fields static int EVAL_BODY_INCLUDE Evaluate body into existing out stream. static int EVAL_PAGE Continue evaluating the page. static int SKIP_BODY Skip body evaluation. static int SKIP_PAGE Skip the rest of the page.

Interface Tag Methods int doStartTag() Called by JSP runtime for Tag handler to process the start tag for this instance. int doEndTag() Called by JSP runtime after returning from doStartTag(). The body of the action may or may not have been evaluated, depending on the return value of doStartTag().

Interface Tag Methods Tag getParent() Get the parent (closest enclosing tag handler) for this tag handler. void release() Called on a Tag handler to perform any cleanup operation.

Interface Tag Methods void setPageContext(PageContext pc) Set the current page context. Invoked before doStartTag() to set the page context. void setParent(Tag parent) Set the parent (closest enclosing tag handler) of this tag handler. Invoked by the JSP runtime, prior to doStartTag(), to pass a tag handler a reference to its parent tag.

Class TagSupport  

A utility base class for defining new tag handlers implementing Tag interface. The TagSupport class implements the Tag and IterationTag interfaces and adds additional convenience methods including getter methods for the properties in Tag

Template for Tag Without Body import java.io.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class HelloTag extends TagSupport { public int doStartTag() throws JspException{ try { // Java code } catch (IOException ioe) {

Template for Tag Without Body throw new JspException("Error: " + ioe.getMessage()); } return SKIP_BODY; } public int doEndTag() throws JspException { return EVAL_PAGE; } }

Template for Tag With Body import java.io.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class HelloTag extends TagSupport { public int doStartTag() throws JspException{ try { // Java code } catch (IOException ioe) {

Template for Tag With Body throw new JspException("Error: " + ioe.getMessage()); } return EVAL_BODY_INCLUDE; } public int doEndTag() throws JspException { return EVAL_PAGE; } }

Tag With Attributes    

Also called parameterized tags. Attributes for customizing behavior of tag. Attributes are modeled as JavaBeans properties. To add an attribute to tag: Need a member variable in class to represent the attribute. Add a setter method for the attribute.

Tag Life Cycle O b t a in h a n d le r d o S ta r tT a g ( ) S et p r o p e r t ie s

s e tP a g e C o n te x t( ) s e tP a r e n t( )

S K IP _ B O D Y

E V A L _ B O D Y _ IN C L U D E

P ro c ess b o d y

S e t a t t r ib u t e v a lu e s S K IP _ P A G E

d o E n d T ag ()

EVAL_PAG E

r e le a s e ( )

r e le a s e ( )

S to p

C o n t in u e

Example A website wants a consistent number and type of fonts. There are 20 developers all with their own opinion on what fonts to use. Custom font tag will need a body, as text will have to go between its start and end tag. The tag should have two attributes to alter its color and size.

MyFontTag.java package test; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.TagSupport; public class MyFontTag extends TagSupport { private String size ="2"; // default size is 2 private String color="#0000FF"; // default color is blue public void setSize(String str) { this.size = str; } public void setColor(String str) { this.color = str; }

MyFontTag.java public int doStartTag() throws JspException { try { pageContext.getOut().print(""); } catch (Exception e) { throw new JspException(e.toString()); } return (EVAL_BODY_INCLUDE); }

MyFontTag.java public int doEndTag() throws JspException { try { pageContext.getOut().print("
"); } catch (Exception e) { throw new JspException(e.toString()); } return (EVAL_PAGE); // check with SKIP_PAGE }

MyFontTag.java public void release() { super.release(); } } Note:

The font will always be Arial, Helvetica, sans-serif as this is not an attribute in our tag, but explicitly hard coded. Its color and size can be altered.

Tag Library Descriptor  



Tag syntax is specified by means of Tag Library Descriptor (TLD) Specifies mapping between tag names and classes and how the tag will be used by JSP runtime that executes tag. TLD specifies tag attributes - Attribute names - Required vs. optional - Compile-time vs. run-time values

Tag Library Descriptor 



The <shortname> tag specifies how the tag library is going to be referenced from JSP page. The tag can be used as a unique identifier for tag library.

Tag Library Descriptor 

values can be i) empty: tag does not has body ii) tagdependent: any body of the tag would be handled by the tag itself, and it can be empty. iii) JSP: meaning that the JSP container should evaluate any body of the tag, but it can also be empty.

Tag Library Descriptor   

Tags without bodies must declare that their body content is empty If contents of tags are JSP, bodycontent should be declared as JSP bodycontent is tagdependent if tag will interpret the contents of the body as nonJSP (for instance an SQL statement)

Tag Library Descriptor 

Body content containing custom and core tags, scripting elements, and HTML text is categorized as JSP; all other types of body content are tagdependent. Note that the value of this element does not affect the interpretation of the body. The bodycontent element is only intended to be used by an authoring tool to present the content of the body.

Tag Library Descriptor tag is when set to false specifies that no run time evaluation is required.  Request-time attribute values must be JSP expressions: ”>  Only name and tagclass are mandatory all other are optional. 

Mytaglib.tld 1.0 <jspversion>1.1 <shortname>ctag myfont test.MyFontTag JSP

Mytaglib.tld color <required>false false size <required>false false


Referencing Tags 1.

2. 3.

Reference the tag library descriptor of an unpacked tag library using taglib directive <%@ taglib uri="/WEB-INF/jsp/mytaglib.tld" prefix="first" %> Reference a JAR file containing a tag library <%@ taglib uri="/WEB-INF/myJARfile.jar" prefix='first" %> Define a reference to the tag library descriptor from the webapplication descriptor (web.xml) and define a short name to reference the tag library from the JSP. mytags /WEB-INF/jsp/ mytaglib.tld In JSP <%@ taglib uri=“mytags" prefix='first" %>

The Custom Tag Library Architecture

CustomTag1.jsp <TITLE>Tag Lib Example <%@ taglib uri="mytaglib.tld" prefix="ctag" %> To make use of custom tag, in JSP write…
With default attributes
Or if you want to change the values from default
With given attributes

Page Compilation

Page C o m p ile r

t a g l i b d ir e c t iv e ?

c u s to m ta g ?

new TLD?

lo a d T L D

v a lid a t e a t t r ib u t e s y n t a x T a g E x t r a In f o ?

id e n t if y s c r ip t in g v a r ia b le s a s s o c ia t e v a r ia b le n a m e s a n d c la s s e s

Page Execution

R equest

t a g l i b d ir e c t iv e ?

c u s to m ta g ?

n o a c t io n r e q u ir e d

n e w ta g ?

lo a d t a g h a n d le r a d d in s t a n c e ( s ) t o r e s o u r c e p o o l

R esponse

o b t a in h a n d le r f r o m p o o l in it ia liz e h a n d le r f o r t a g e x e c u t e h a n d le r r e t u r n h a n d le r t o p o o l

Running JSP 1. 2. 3. 4. 5. 6. 7. 8. 9.

Create folder “test” in ApacheHome\webapps\examples\jsp. Store file MyFontTag.java in folder “test”. Include servlet.jar in classpath. Location is ApacheHome\common\lib\servlet.jar Compile MyFontTag.java Store Mytaglib.tld in folder “test” Set classpath ApacheHome\webapps\examples\jsp in a new window before starting tomcat server. Set classpath ApacheHome\common\lib\servlet.jar in a new window before starting tomcat server. Start tomcat server Run JSP http://localhost:7001/examples/jsp/test/CustomTag1.jsp

Result To make use of custom tag, in JSP write… With default attributes

Or if you want to change the values from default

With given attributes

Notes 



For large project with many developers and many custom tags in TLD is to create a jar (e.g MyTagLib.jar) file containing the custom tag classes and the TLD (TLD “taglib.tld”, and it should be placed into /META-INF of jar file) Once the jar file is in class path custom tags can be referenced in JSP via <%@ taglib uri="MyTag.jar" prefix=“ctag" %>

Notes 

In webapps/examples/WEB-INF/web.xml add entry MyTag /jsp/test/mytaglib.tld In JSP <%@ taglib uri="MyTag" prefix=“ctag" %>

Tag Library 

A tag library is a collection of JSP custom tags. Tag Library JAR directories containing tag handler packages

MANIFEST.MF META-INF

taglib.tld

Tags With Body A tag handler for a tag with a body is implemented differently depending on whether the body needs to be evaluated once or multiple times.  Body Evaluation Single Evaluation Multiple Evaluation E.g. of iteration Iterate rows, query, search results 

Tags With Body Single Evaluation

Multiple Evaluation

Implement interface Tag

Implement interface BodyTag

doStartTag method needs to return EVAL_BODY_INCLUDE, and if it does not need to be evaluated at all then it should return SKIP_BODY.

Typically, override doInitBody and doAfterBody methods. The doInitBody is called after the body content is set but before it is evaluated, and the doAfterBody is called after the body content is evaluated.

Body Evaluation 



A tag handler for a tag with a body is implemented differently depending on whether the body needs to be evaluated once or multiple times. Body Evaluation Single Evaluation Multiple Evaluation

BodyTag Interface 



Complex tags implement the BodyTag interface - Generate page content - Conditionally execute body content - Process content generated by body - Repeat execution of body content - Conditionally halt page execution BodyTagSupport class provides default implementation

BodyTag Interface 

The BodyTag interface extends Tag by defining additional methods that let a tag handler access its body. The interface provides three new methods: - setBodyContent: Creates body content and adds to the tag handler - doInitBody: Called before evaluation of the tag body - doAfterBody: Called after evaluation of the tag body

BodyTag Interface

Tag

Iteration Tag

Body Tag

implements

implements

TagSupport

BodyTagSupport

BodyTag Life Cycle O b t a in h a n d le r I n it ia liz e b o d y c o n te n t S et p r o p e r t ie s

s e tP a g e C o n te x t( ) s e tP a r e n t()

d o S ta r tT a g ( )

s e tB o d y C o n te n t( ) d o I n it B o d y ( )

EVAL_BO D Y_T AG P ro c ess b o d y

S K IP _ BO D Y S e t a t t r ib u t e v a lu e s

d o A f te r B o d y ( ) S K IP _ BO D Y S K IP _ P A G E

d o E n d T ag ()

EVAL_PAG E

r e le a s e ( )

r e le a s e ( )

S to p

C o n t in u e

EVAL_BO D Y_T AG

Single Evaluation package test; import java.io.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class ToLowerCaseTag extends BodyTagSupport { public int doAfterBody() throws JspException { try { BodyContent bc = getBodyContent(); String body = bc.getString();

Single Evaluation JspWriter out = bc.getEnclosingWriter(); if(body != null) { out.print(body.toLowerCase()); } } catch(IOException ioe) { throw new JspException(ioe.getMessage()); } return SKIP_BODY; } }

Single Evaluation TLD

tolowercase test.ToLowerCaseTag JSP To lower case tag

Single Evaluation <TITLE>To Lower Case Example JSP Custom Tag Programming
<%@ taglib uri="mytaglib.tld" prefix="ctag" %> JSP Custom Tag Programming

Single Evaluation Result JSP Custom Tag Programming jsp custom tag programming

Single Evaluation Result JSP Custom Tag Programming jsp custom tag programming

Single Evaluation <TITLE>To Lower Case Example JSP Custom Tag Programming
<%@ taglib uri="mytaglib.tld" prefix="ctag" %> JSP Custom Tag Programming

Single Evaluation Result JSP Custom Tag Programming jsp custom tag programming

Multiple Evaluation Example ... taglib uri="mytags" prefix="codecamp" %>
...

Multiple Evaluation package test; import java.io.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class IterTag extends BodyTagSupport { int times = 0; BodyContent bodyContent; public void setTimes(int times) { this.times = times; } public int doStartTag() throws JspException { return times >1?EVAL_BODY_AGAIN:SKIP_BODY; }

Multiple Evaluation public void setBodyContent(BodyContent bodyContent) { this.bodyContent = bodyContent; } public int doAfterBody() throws JspException { if (times >1) { times--; return EVAL_BODY_AGAIN; } else { return SKIP_BODY; } }

Multiple Evaluation public int doEndTag() throws JspException { try { if(bodyContent != null) { bodyContent.writeOut (bodyContent.getEnclosingWriter()); } } catch(IOException e) { throw new JspException(e.getMessage()); } return EVAL_PAGE; } }

Multiple Evaluation iter test.IterTag JSP Tag with body and parameter times <required>true true

Multiple Evaluation <TITLE>To Lower Case Example JSP Custom Tag Programming
<%@ taglib uri="mytaglib.tld" prefix="ctag" %> JSP Custom Tag Programming


Multiple Evaluation Result JSP Custom Tag Programming jsp custom tag programming jsp custom tag programming jsp custom tag programming jsp custom tag programming jsp custom tag programming

Cooperating Tags <x:query id="balances"> SELECT account, balance FROM acct_table where customer_number = <%=request.getCustno()%>

Examples Ex. For displaying today’s date according to locale. <%@ taglib uri="/WEB-INF/lib/DateTagLib.tld" prefix="abc" %> <TITLE>Date tag example Today is

Scripting variables package test; import java.util.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public final class SecondTag implements Tag { private PageContext pc = null; public void setPageContext(PageContext p) { pc = p; } public void setParent(Tag t) {} public Tag getParent() { return null; }

Scripting variables public int doStartTag() throws JspException { Calendar cal = Calendar.getInstance(); pc.setAttribute("time", cal.getTime().toString()); return EVAL_BODY_INCLUDE; } public int doEndTag() throws JspException { return EVAL_PAGE; } public void release() { pc = null; } }

Scripting variables package test; import javax.servlet.jsp.tagext.*; public class SecondTagTEI extends TagExtraInfo { public VariableInfo[] getVariableInfo(TagData data) { return new VariableInfo[] { new VariableInfo("time", "java.lang.String", true, VariableInfo.NESTED) }; } }

Scripting variables secondtag test.SecondTag test.SecondTagTEI JSP Your second JSP Tag

Scripting variables SecondTag <%@ taglib uri="mytaglib.tld" prefix="star"%> <star:secondtag>

Date value retrieved from JSP Tag:<%= time %>



Examples 



JSP tags are especially suited for repetitive tasks such as looping over an array, doing browser checking, and validation. Creating hyperlinks is another such repetitive task. Multi-destination hyperlinks.

Examples

Examples 

<%@ taglib uri="http://jakarta.apache.org/taglibs/dbta gs" prefix="sql" %> <%-- open a db connection --%> <sql:connection id="conn1"> <sql:url>jdbc:mysql://localhost/test <sql:driver>org.gjt.mm.mysql.Driver

Examples <%-- insert a row into the database -%> <sql:statement id="stmt1" conn="conn1"> <%-- set the SQL query --%> <sql:query>insert into counters(page,hitCount) values('<%=request.getRequestURI()%>', 0)

Examples <%-- the insert may fail, but the page will continue --%> <sql:execute ignoreErrors="true"/>

Examples <%-- update the hit counter --%> <sql:statement id="stmt1" conn="conn1"> <%-- set the SQL query --%> <sql:query>update counters set hitCount = hitCount + 1 where page like '<%=request.getRequestURI()%>' <sql:execute/> <%– Execute query --%>

Related Documents

Jsp 1.2 Custom Tags
July 2020 7
Jsp Custom Tags
November 2019 9
07 Basic Custom Tags
November 2019 8
07-basic-custom-tags
July 2020 8
1creating Custom Tags
November 2019 7