JSP Custom Tag Library

Source: Internet
Author: User
Tags tld

Today is nothing to do, so think of their previous use of the label, whether it is the jstl,struts label or SPRINGMVC label, used to feel very convenient, so I want to try to define their own label.

Let's share with you the results of today. To customize labels and use labels, you need the following steps:

1, define their own label resolution class, is generally inherited TagSupport class (Servlet-api.jar), override the class of doStartTag () or Doendtag () method;

2. Define. tld files;

3. Declare the tags to be used in Web. XML (or do not declare them);

4. Use a custom label in the JSP.

Here is an example to give you a detailed explanation:

1. Define your own first tag resolution class:

Package Com.jrj.tag.example;import Java.io.ioexception;import Javax.servlet.jsp.jspexception;import Javax.servlet.jsp.tagext.TagSupport, @SuppressWarnings ("Serial") public class Firsttag extends tagsupport{@ overridepublic int Doendtag () throws Jspexception {try {pagecontext.getout (). Write ("Hello World");} catch (IOException E {//TODO auto-generated catch Blocke.printstacktrace ();} return eval_page;}}


2. Create a new Tagfile folder under Web-inf, and then create a new example.tld in the file with the following contents:

<?xml version= "1.0" encoding= "iso-8859-1"? ><! DOCTYPE taglib Public "-//sun Microsystems, Inc.//dtd JSP Tag Library 1.2//en" "Http://java.sun.com/dtd/web-jsptaglibrar Y_1_2.dtd "><taglib><tlib-version>1.0</tlib-version><jsp-version>1.2</jsp-version ><short-name>em</short-name><uri>http://com.jrj.tag/em</uri><display-name> Example</display-name> <description>em 1.0 library</description><tag><name>out</ name><tag-class>com.jrj.tag.example.firsttag</tag-class><body-content>jsp</ Body-content><description>writer out the Cotentes</description></tag></taglib>


3. If you want to add a label declaration to the Web. xml file, add the following snippet of code to Web. XML:

<jsp-config> <taglib> <taglib-uri>/em</taglib-uri> <taglib-location>/web-inf/tagfil E/example.tld</taglib-location> </taglib></jsp-config>

Note: In these examples explained today, I did not add the above code in Web. XML, if added then in the following JSP reference tag will be different, I hope you notice!

4, the use of tags in the JSP, you need to refer to the tag before use:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" Utf-8 "%><%@ taglib uri=" http://com.jrj.tag/em "prefix=" em "%><! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">

Let me extend to you two other examples, one on conditional expressions and one on iterations and the nesting of tags:

1, about the conditional expression, according to the above for everyone to explain the steps:

1),

Package Com.jrj.tag.example;import Javax.servlet.jsp.jspexception;import javax.servlet.jsp.tagext.tagsupport;@ Suppresswarnings ("Serial") public class Iftag extends tagsupport{private boolean condition; @Overridepublic int doStartTag () throws Jspexception {return condition? Eval_body_include:skip_body;} public Boolean iscondition () {return condition;} public void Setcondition (Boolean condition) {this.condition = condition;}}


2), add the following content in Example.tld:

<tag><name>if</name><tag-class>com.jrj.tag.example.IfTag</tag-class>< Body-content>jsp</body-content><description>if condition</description><attribute> <name>condition</name><required>true</required><rtexprvalue>true</rtexprvalue ><type>boolean</type><description>condition</description></attribute></tag >


3), use JSP, JSP modified to become as follows:

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" Utf-8 "%><%@ taglib uri=" http://com.jrj.tag/em "prefix=" em "%><! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">


2. Nesting of iterations and tags

1), Label parsing class

package com.jrj.tag.example;import java.util.collection;import java.util.iterator;import  javax.servlet.jsp.jspexception;import javax.servlet.jsp.tagext.bodytagsupport; @SuppressWarnings ("Serial") public class foreachtag extends bodytagsupport {@SuppressWarnings ("Rawtypes") private  Collection items;private String var; @SuppressWarnings ("Rawtypes") private iterator  it; @Overridepublic  int dostarttag ()  throws jspexception {if (items==null| | Items.size () ==0) return skip_body;it = items.iterator (); if (It.hasnext ()) { Pagecontext.setattribute (Var, it.next ());} Return eval_body_include;} @Overridepublic  int doafterbody ()  throws jspexception {if (It.hasnext ()) { Pagecontext.setattribute (Var, it.next ()); return eval_body_again;} Return skip_body;} @Overridepublic  int doendtag ()  throws jspexception {return eval_page;} @Suppresswarnings ("Rawtypes") Public collection getitems ()  {return items; @SuppressWarnings ("Rawtypes") Public void setitems (Collection items)  {this.items =  items;} Public string getvar ()  {return var;} Public void setvar (String var)  {this.var = var;}}

2), add the following content in Example.tld:

<tag><name>foreach</name><tag-class>com.jrj.tag.example.ForEachTag</tag-class> <body-content>jsp</body-content><description>foreach the collection</description>< attribute><name>var</name><required>true</required><rtexprvalue>true</ rtexprvalue></attribute><attribute><name>items</name><required>true</ Required><rtexprvalue>true</rtexprvalue></attribute></tag>


3), JSP use, JSP content as follows:

<%@ page language= "java"  contenttype= "Text/html; charset=utf-8"  pageEncoding= " Utf-8 " %><%@ taglib uri=" http://com.jrj.tag/em " prefix=" em " %><%@  Page import= "java.util.*"  %><%string path = request.getcontextpath (); Arraylist<string> values = new arraylist<string> (); Values.add ("zhouming"); Values.add ("Xiaoshou"), Values.add ("Minggou");p agecontext.setattribute ("values",  values);%><! doctype html public  "-//w3c//dtd xhtml 1.0 transitional//en"   "HTTP// Www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">


Here are two things you might have questions about: the first is the meaning of the return value of each method in the Java class, and the second is what some elements in the TLD file mean.

1, when we create a custom label, the method of copying the parent class is to pay attention to the meaning of the return value, the different return values represent different processing, the following is the meaning of the different return values:

Eval_body_include: Reads the BODY into the existing output stream, the doStartTag () function is available

Eval_page: Continue processing page, Doendtag () function available

Skip_body: Ignores handling of BODY, doStartTag () and Doafterbody () functions are available

Skip_page: Ignoring the processing of the remaining pages, the Doendtag () function is available

Eval_body_tag: Abolished, replaced by eval_body_buffered

Eval_body_buffered: Request Buffer,

The Bodycontent object obtained by the Setbodycontent () function handles the body of the tag,

If the class implements Bodytag, then doStartTag () is available, otherwise illegal

2. If we need to loop through the contents of the body, our custom tag parsing class needs to implement the Bodytag interface or inherit the Bodytagsupport class

3. In our custom TLD file, be aware of the value of the Rtexprvalue (run-time Expression value) element under the attribute element, if true, indicating that the value of the property can be specified directly or

specified by an expression, if the value is false, the value of the property must be specified directly.

The above is the basic steps of the custom label, I do today in the process of learning from the jstl of the implementation process and the Internet to find some information. I think this is a very efficient way, if you have any more efficient ways,

Can share out, we progress together! We'll see you next time!


This article is from the "technology endless, learning needs more Brain" blog, please be sure to keep this source http://wenqiangv.blog.51cto.com/7889138/1433218

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.