JSP custom tag (1)

Source: Internet
Author: User
Tags tld
Document directory
  • 1. attributes need to be added to the original hellotag. java.
  • 2. Add the attribute description to the TLD file:
I. Introduce tags

In fact, we have used several tags in JSP, such as <JSP: Forward> and <JSP: Include>. These tags are pre-defined. If we need to customize tags, you need to learn label programming.

The advantage of tag programming is flexibility + encapsulation.

Flexibility is embodied in attribute assignment and can be assigned any value. For example, <JSP: Forward page = "A"> // any URL can be assigned to;

Encapsulation is embodied in the encapsulation of internal behavior. Because labels are implemented by a class, the class method can contain any complicated action.

ThereforeLabels are used to use as few scriptlet as possible in JSP;

For example:

 <table> <% for(int i=0;i<10;i++){ %> <tr> <%  for(int j=0;j<10;j++){ %>  <td><%=i*j%></td> <%  } %>  </tr> <% } %> </table>

This code is very confusing, but if the code is encapsulated in a tag through the tag, the code is much clearer.

The following is the JSP page effect after I encapsulate through tags;

<%@ page contentType="text/html" pageEncoding="GBK"%><%@ taglib prefix="xiazdong" uri="xiazdong"%>

Is it greatly shortened ?? Let's take a look at what I did behind the scenes ....

Tabletagsupport. Java

package org.tagext;import javax.servlet.jsp.tagext.*;import javax.servlet.jsp.*;public class TableTagSupport extends TagSupport{private String row;private String col;public String getRow(){return row;}public String getCol(){return col;}public void setRow(String row){this.row = row;}public void setCol(String col){this.col = col;}public int doStartTag()throws JspException{JspWriter out = super.pageContext.getOut();try{out.println("<table border=\"3\"> ");for(int i=0;i<Integer.parseInt(row);i++){out.println("<tr>");for(int j=0;j<Integer.parseInt(col);j++){out.println("<td>"+i*j+"</td>");}out.println("</tr>");}out.println("</table>");}catch(Exception e){}return TagSupport.SKIP_BODY;}}

Is it amazing... Then let's take a look at the implementation process.

Note: before writing tags,The jsp-api.jar file in Tomcat \ Lib must be configured in classpath;


Ii. Basic tag writing 1. tagsupport class

If you want to write a label class, you must inheritJavax. servlet. jsp. tagext. tagsupport;

Tagsupport provides many common methods:

(1) Public intDostarttag() Throws jspexception; // call when the tag starts

Returns skip_body (skip the label body) and eval_body_include (execute the label body)

(2) Public intDoendtag() Throws jspexception; // call when the Tag ends

It can return skip_page (stop execution immediately) and eval_page (JSP runs normally );

(3) intSkip_body; // Skip the label body

(4) intEval_body_include; // Execute the label body

(5) intEval_body_again; // Re-execute the label body, mainly because of the iterative output of the Set, which can only be used in doafterbody;

(6) Public intDoafterbody() Throws jspexception; // The function called after a TAG body is executed;

Returns skip_body (end label body) and eval_body_again (repeat the label body)

(7)Jspwriter out = super. pagecontext. getout (); // gets the output stream to the webpage;

For example, what do these functions and constants mean:

<Xiazdong: Hello> <! -- Label header --> 

The execution process is as follows:

(1) dostarttag (); <xiazdong: Hello> is called. If it is eval_body_include, continue; if it is skip_body, execute (4)

(2) execute the TAG body;

(3) If doafterbody is implemented, execute; If skip_body is returned, execute (4); If eval_body_again is returned, execute doafterbody again;

(4) doendtag (): Tag tail call;

2. Create a non-attribute tag

For clarity, we will illustrate it with examples.

Code Example 1: Display Hello world;

1. Compile hellotag. Java


package org.tagext;import javax.servlet.jsp.tagext.*;import javax.servlet.jsp.*;public class HelloTag extends TagSupport{public int doStartTag()throws JspException{JspWriter out = super.pageContext.getOut();try{out.println("

Note:

(1) javax. servlet. jsp. tagext. tagsupport, which must be remembered;

(2) jspwriter out = super. pagecontext. getout ();

(3) Public int dostarttag () throws jspexception; it must be remembered;

2. Compile xiazdong. TLD


TLD files are tag description files and the core of tag programming. They are used to describe custom tag names, implementation classes of tags, tag bodies, and description attributes;

A tld file is actually similar to a tag library, which can describe many tags.

<Tag> <Name> Hello </Name> <! -- Indicates that the tag name is similar to forward in <JSP: Forward> --> <tag-class> org. tagext. hellotag </Tag-class> <! -- Tag class --> <body-content> Empty </body-content> <! -- Whether the TAG body exists --> </Tag>

Format description;

* The TLD file template is as follows: (because the content above the TLD file is not very important, you can copy and paste it directly)

<? XML version = "1.0" encoding = "UTF-8"?> <Taglib xmlns = "http://java.sun.com/xml/ns/j2ee" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation = "http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd" version = "2.0"> <tlib-version> 1.0 </tlib-version> // insert tag description </taglib>


3. Write ing in Web. xml


The purpose of writing ing is similar to configuring a ing address for a webpage for convenient access;

For example, to access/A/B/C/D/E/F/G/1.tld, we only need to use "a" to represent a long string of file paths and names;

<jsp-config><taglib><taglib-uri>xiazdong</taglib-uri><taglib-location>/WEB-INF/classes/xiazdong.tld</taglib-location></taglib></jsp-config>



4. Compile JSP pages and use custom tags


<% @ Taglib prefix = "" uri = "" %>Prefix is similar to JSP in <JSP: Forward>. The URI uses the ing mentioned above;

<%@ page contentType="text/html" pageEncoding="GBK"%><%@ taglib prefix="xiazdong" uri="xiazdong"%>3. Create an attribute tag

In fact, there is no big difference between production with attributes and production without attributes,

1. attributes need to be added to the original hellotag. java.

If the property is shown as <xiazdong: Hello id = "" format = ""/>, you must add two attributes in hellotag. Java: ID and format;

Shape:

Class hellotag extends tagsupport {private string ID; private string format; // setter and getterpublic int dostarttag () throws jspexception {}}

When you use tags and assign values to the ID and format attributes, the setter method is automatically called to assign values to the IDs and formats in the hellotag class;

2. Add the attribute description to the TLD file:

The property description is shown in the following figure:

<Body-content> Empty </body-content> is followed by <attribute> <Name> name </Name> <! -- Attribute name --> <required> true </required> <! -- Property required? --> <rtexprvalue> Empty </rtexprvalue> <! -- Whether expression language is supported --> </attribute>

Code example:


Hellotag. Java

Package Org. tagext; import javax. servlet. JSP. tagext. *; import javax. servlet. JSP. *; public class hellotag extends tagsupport {private string name; private string age; Public String getname () {return name;} Public String getage () {return age ;} public void setname (string name) {This. name = Name;} public void setage (string age) {This. age = age;} public int dostarttag () throws jspexception {jspwriter out = super. pagecontext. getout (); try {out. println ("

Xiazdong. TLDAttribute description: name, required or not, and Expression Language supported

<?xml version="1.0" encoding="UTF-8" ?><taglib xmlns="http://java.sun.com/xml/ns/j2ee"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"    version="2.0">  <tlib-version>1.0</tlib-version>  <short-name>x</short-name>  <tag><name>hello</name><tag-class>org.tagext.HelloTag</tag-class><body-content>empty</body-content><attribute><name>name</name><required>true</required><rtexprvalue>empty</rtexprvalue></attribute><attribute><name>age</name><required>true</required><rtexprvalue>empty</rtexprvalue></attribute>  </tag></taglib>

Hellotag. jsp

<%@ page contentType="text/html" pageEncoding="GBK"%><%@ taglib prefix="xiazdong" uri="xiazdong"%>

Iii. Differences between iterationtag and tag interface the tag interface has only some basic tag programming methods, while the iterationtag interface is used for iterative output, such as eval_body_again;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.