Chapter 1 Outline What are the custom tags? How to Write Custom Tags? What is the TLD file? The Tag Handler Life Cycle. Using Custom tag in a JSP page. The role of deployment descriptor.
• They are special tags that are used to perform customized actions • You can separate the presentation part of a JSP page from the business rule implementation (Java code) code).
• Only three action elements—jsp:useBean, jsp:setProperty and getProperty getProperty. • In some sit situations, ations we e ha have e to resort to using sing code in a JSP page
• JSP 1.1 defined a new feature: custom tags that can be used to perform custom actions. • Custom tags -unlike java beans - have access to all the objects available to JSP pages pages, and custom tags can be customized using attributes
• There are mainly 4 steps 1-Design our own Custom Tag 2- Create a TLD file named taglib.tld, and save it in the WEB-INF directory. 3 Compile, 3C il and d deploy d l the th Java J class l (your ( tag t Handler). 4 Create a JSP file 4-Create file, import your custom tag then use it.
A tag library descriptor (TLD) file is an XML document that defines a tag library and its tags. A TLD file is to custom tag handlers what a Web deployment descriptor is to servlets. A TLD file contains the root element element. This element can have the following subelements: • • • • • •
tlibversion jspversion shortname i f info uri tag JavaTM Education & Technology Services
• Th The tlibversion tlib i element l t specifies ifi th the version i number b off the tag library in the following format: ([0-9])* (("." [0-9])? (("." [0-9])? (("." [0-9])? ([0-9])
• The shortname element specifies a short name for the tag library. The value for this element must begin with a letter and must not contain blank space.
• The info element contains the information used for documentation purposes Its default value is an empty string purposes. string.
• The uri element specifies the link to an additional source of documentation for the tag library.
• The tag element is the most important element in a tag library. You can specify more than one tag element in the same TLD file.
IIs the h Java J class l that h is i linked li k d to a custom tag and d gets invoked every time the JSP container encounters the custom tag. The tag handler is so named because it handles the processing of the tag The tag handler must implement an interface in the javax servlet jsp tagext package or extend one of the classes in javax.servlet.jsp.tagext the same package. The most important interfaces are : • Tag • Iteration Tag • Body Tag
1. The JSP container obtains an instance of the tag handler from the pool or creates a new one. It then calls the setPageContext setPageContext, passing a PageContext object representing the JSP page where the custom tag is found. 2. The e JS JSP co container a e then e ca calls s the e se setParent a e method. e od This method passes a tag object, which represents the closest tag enclosing the current tag handler.
you first fi t need d to t use a taglib t lib di directive ti iin your page. The uri attribute specifies an absolute or relative URI that uniquely q y identifies the tag g library y descriptor p associated with this prefix Next to use it : – fi N / – body – "13"/>
• The JSP container can find the name and location of the TLD file by looking up the deployment descriptor • This Thi is i preferable f bl but b t nott obligatory bli t • Example: • t lib – /myTld – /WEB-INF/taglib.tld /WEB INF/taglib tld
The tag handler will take the form: public class DoublerTag p g implements p Tag g{ private int number; public void setNumber(int number) { this.number = number;}} PageContext pageContext; public void setParent(Tag t) {} public void setPageContext(PageContext p) { pageContext = p;} public void release() {} public Tag getParent() {return null;} public int doStartTag() S () {{try { JspWriter out = pageContext.getOut(); out.println("Double of " + number + " is " + (2 * number));} catch(Exception t h(E ti e)) {} return EVAL_BODY_INCLUDE; }public int doEndTag() throws JspException { return EVAL EVAL_PAGE;} PAGE;} JavaTM Education & Technology Services
• The IterationTag interface extends the Tag interface. • It adds a new method called doAfterBody and a static fi l integer final i t EVAL_BODY_AGAIN. EVAL BODY AGAIN • This method is invoked after the doStartTag method and can return either the Tag Tag.SKIP_BODY SKIP BODY or IterationTag.EVAL_BODY_AGAIN. • If the latter is returned, returned the doAfterBody is called again again. If the return value is Tag.SKIP_BODY, the body will be skipped pp and the JSP container will call the doEndTag g method.
• A JSP custom t tag t can have h a body b d content, t t such h as the th following tag: – x %> – This is the body content • When you use the Tag and IterationTag interfaces, you cannot manipulate the body content. You don't even have access to it. • This Thi could ld b be achieved hi db by: – The BodyTag Interface – The Th BodyContent B d C t t Class Cl
Example import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public bli class l C CapitalizerTag it li T extends t d B BodyTagSupport d T S t{ public int doAfterBody() { String content = bodyContent.getString(); bodyContent getString(); try{ p out = bodyContent.getEnclosingWriter(); y g g () JspWriter out.print(content.toUpperCase()); } catch(Exception t h(E ti e)) {} return SKIP_BODY; } }
• JSTL ttags are XML XML, th they cleanly l l and d uniformly if l bl blend d • •
• •
into a page's HTML markup tags. The main JSTL tag libraries include most functionality that would be needed in a JSP page. JSTL tags are easier for non-programmers and inexperienced programmers to use effectively effectively, because they do not require any knowledge of programming or Java. JSTL ttags can reference f objects bj t iin th the requestt and d session without knowing the object's type and no casting is required. JSP's EL (Expression Language) makes it easy to call getter and setter methods on Java objects. JavaTM Education & Technology Services
JSTL main packages (Cont’d) • The core library includes tags for the following uses: – Accessing and modifying data in memory – Making decisions in your pages – Looping over data
• The e XML library b a y includes c udes tags for o tthe e following o o g pu purposes: poses – Parsing (that is, reading) XML documents – Printing parts of XML documents – Making decisions in your page based on the contents of an XML document
• The formatting and internationalization library includes tags for these uses: – Reading and printing numbers – Reading and printing dates (with support for time zones) – Helping your application work with more than one language
Expression Language • How Expression Language looks like ? • It starts t t with ith ${ • Example :
and d ends d with ith }
– ${ 1+2}
• NB: Expression Language can be understood inside JSTL Tags and JSP tags as well well. • Types of data read by EL? • Scoped Variables • Request Parameters
Expression Language (cont’d) • The default of scopes: Page-request-session then finally application • To be able to specify your variable scope : – – – –
${pageScope.username} ${p g p } ${requestScope.username} ${sessionScope.username} ${applicationScope.username}
cookie: ki JSTL d doesn’t ’t give i you a way tto sett cookies ki (backend job) but u can retrieve cookies. header: read all client header headerValues: all values initParam: to access initialization parameters pageContext: more details about your page
• Take care : ${ …} must include the entire expression. • E Example l off iinvalid lid statments: t t t – ${ ${user.weight} gt ${user.IQ} } – ${user.weight} ${user weight} gt ${user ${user.IQ} IQ} • Only we can say : – ${user.weight ${user weight gt user.IQ} user IQ}
• Boolean operations and parentheses • ${ (param.month == 5 or param.month == 6) and (param.day == 25) }
Complex conditional tags • Mutually exclusive conditions with and ……. ,, similar to switch statements • The c:choose tag is simple: it takes no attributes and serves only as a container • for and tags. g Just as HTML’s
• The tag is similar to : it takes a single test attribute. • For each tag, no more than one child tag can succeed succeed. • succeeds only if all its sibling tags (those with the same parent tag) have failed.
1 1h and d th i ttags cannott appear outside a tag. 2- There There’s s a flip side to this rule: a tag cannot have any direct children (or nonwhite space text) except or tags. 3- If occurs, it must follow all the tags; it may not come before any of them. 4 Every must have at least one and 4no more than one .
• you can determine information about the current item’s position within the overall loop: is it first, last, or somewhere in the middle? • You can loop over only a part of collection using index
• It supercedes , providing all the functionality of the core JSP tag but also adding new features lets you store the retrieved text in a scoped features, variable instead of printing it.
• • – You can retrieve files from another web application by specifying that web application’s name using the i t tag’s t ’ context t t attribute tt ib t .
• Accessing A i metadata t d t : u can gett column l names and d row count through rowCount, columnNames attributes . • Example: SELECT NAME, IQ FROM USERS WHERE IQ > 120