Go Introduction to [Java] custom tags

Source: Internet
Author: User

Role: Custom tags are primarily used to remove Java code from JSP pages.

Implementation: You need to complete the following two steps:

    1. Write a Java class that implements the Tag interface and move the page Java code into this Java class. (Label processing Class)
    2. Write a tag library descriptor (TLD) file that describes the label processor class as a label in the TLD file.

Code: Create a new Day11 project, create a new Cn.itcast.web.tag package in the SRC directory, viewiptag java file

 PackageCn.itcast.web.tag;Importjava.io.IOException;Importjavax.servlet.http.HttpServletRequest;Importjavax.servlet.jsp.JspException;ImportJavax.servlet.jsp.JspWriter;ImportJavax.servlet.jsp.tagext.TagSupport; Public classViewiptagextendsTagSupport {@Override Public intdoStartTag ()throwsjspexception {httpservletrequest request= (HttpServletRequest) This. Pagecontext.getrequest (); JspWriter out= This. Pagecontext.getout (); String IP=request.getremoteaddr (); Try{out.print (IP); } Catch(IOException e) {Throw NewRuntimeException (e); }        return Super. doStartTag (); }}

Then create a new itcast.tld in the Webroot\web-inf directory

<?XML version= "1.0" encoding= "UTF-8"?><!--part of this code is from: X:\apache-tomcat-7.0.77-src\webapps\examples\WEB-INF\jsp2\jsp2-example-taglib.tld Licensed to the  Apache software Foundation (ASF) under one or more contributor license agreements.  See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License");  You are not a use of this file except in compliance with the License.  Obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 unless required by applicable or agreed to writing, software distributed under the License are distributed on a "as is" BASIS, without warranties  or CONDITIONS of any KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -<taglibxmlns= "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">        <Description>A Tag Library exercising simpletag handlers.</Description>    <tlib-version>1.0</tlib-version>    <Short-name>Itcast</Short-name>    <URI>http://www.itcast.cn</URI>        <Tag>        <Description>Output Client IP</Description>        <name>Viewip</name>        <Tag-class>Cn.itcast.web.tag.ViewIPTag</Tag-class>        <body-content>Empty</body-content>    </Tag>    </taglib>

This tag can be used in any JSP file.

<%@ Page Language="Java"Import="java.util.*"pageencoding="UTF-8"%><%@ taglib URI="http://www.itcast.cn"prefix="Itcast" %><!DOCTYPE HTML><HTML>  <Head>    <title>Starting page</title>  </Head>    <Body>This is my JSP page.<BR>the IP from the client is:<Itcast:viewip/>  </Body></HTML>

Label Invocation Process:

1. Browser sends JSP page request to WEB server

2. The WEB server begins to interpret the JSP page

3. When you encounter a custom label, first instantiate the label processor class for the label

4. Call the Setpagecontext method to pass the page's PageContext object to the label processor class

5. See if the label has a parent tag, if there is a parent tag, the parent tag as an object, call the SetParent method to pass to the label processor class, if not, pass a null

6. After the initialization of the above tag is completed, the server starts to execute the tag. When you encounter the label's start tag, call the doStartTag method

7. If the label has a label body, then the server will generally execute the label body

8. When the server encounters a JSP page end tag, call the Doendtag method of the Label processor class

9. After the entire label is executed, the server typically calls the release method to release the resources that the label is working on

Method Summary = setpagecontext (PageContext pc) GetParent () setParent () doStartTag () Doendtag () release ()

In the Viewiptag.java class, the doStartTag method defaults to return Super.dostarttag ();

Output label body if rewritten as return Tag.eval_body_include

If rewritten as return tag.skip_body does not output the label body

The Doendtag method defaults to return Super.doendtag ();

Output if rewritten as return tag.eval_page

Stop output if rewritten as return tag.skip_page

If the label body needs to be executed 5 times, write in the Doafterbody method:

@Override Public intdoStartTag ()throwsjspexception {returnTag.eval_body_include;} @Override Public intDoafterbody ()throwsjspexception {intX=5; X--; if(x>0){        returnIterationtag.eval_body_again; }Else{        returnIterationtag.skip_body; }}
//Modify the label body Public classTagDemo4extendsBodytagsupport {@Override Public intdoStartTag ()throwsjspexception {returnbodytag.eval_body_buffered; } @Override Public intDoendtag ()throwsjspexception {bodycontent BC= This. Getbodycontent (); String content=bc.getstring (); Content=content.touppercase (); Try {             This. Pagecontext.getout (). write (content); } Catch(IOException e) {Throw NewRuntimeException (e); }                returnTag.eval_page; }}

Go Introduction to [Java] custom tags

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.