随笔 - 750  文章 - 1  评论 - 107  阅读 - 34万

[转][Java]自定义标签简介

作用:自定义标签主要用于移除 jsp 页面中的 java 代码。

实现:需要完成以下两个步骤:

  1. 编写一个实现 Tag 接口的 Java 类,把页面 java 代码移到这个 java 类中。(标签处理类)
  2. 编写标签库描述符 (tld)文件,在 tld 文件中把标签处理器类描述成一个标签。

代码:新建一个  day11 项目,在 src 目录下新建 cn.itcast.web.tag 包,ViewIPTag Java文件

复制代码
package cn.itcast.web.tag;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

public class ViewIPTag extends TagSupport {

    @Override
    public int doStartTag() throws JspException {
        HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();
        JspWriter out = this.pageContext.getOut();

        String ip = request.getRemoteAddr();
        try {
            out.print(ip);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return super.doStartTag();
    }
}
复制代码

再在 WebRoot\WEB-INF 目录下新建 itcast.tld

复制代码
<?xml version="1.0" encoding="UTF-8" ?>
<!-- 本代码部分内容来自: 
 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 may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "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.
-->

<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">
    
    <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>输出客户端IP</description>
        <name>viewIP</name>
        <tag-class>cn.itcast.web.tag.ViewIPTag</tag-class>
        <body-content>empty</body-content>
    </tag>
    
</taglib>
复制代码

这时候就可以在任意 jsp 文件中使用此标签

复制代码
<%@ 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>
        来自客户端的IP是:<itcast:viewIP/>
  </body>
</html>
复制代码

 标签调用流程:

1. 浏览器给 Web 服务器发送 jsp页面请求

2. Web 服务器开始解释 jsp 页面

3. 遇到自定义标签,首先实例化标签对应的标签处理器类

4. 调用 setPageContext 方法,把页面的 pageContext 对象传递给标签处理器类

5. 看标签是否有父标签,如果有父标签,把父标签作为一个对象,调用 setParent 方法传递给标签处理器类,如果没有,传递一个 null

6. 完成以上标签的初始化工作后,服务器就开始执行标签。这时遇到 标签的开始标签,就调用 doStartTag 方法

7. 如果标签有标签体,这时服务器一般会执行标签体

8. 服务器遇到 jsp页面结束标签,则调用标签处理器类的 doEndTag 方法

9. 整个标签执行完后,服务器一般情况下会调用 release 方法释放标签工作时所占用的资源

Method Summary => setPageContext(PageContext pc) getParent() setParent() doStartTag() doEndTag() release()

 

在 ViewIPTag.java 类中,doStartTag 方法默认是 return super.doStartTag();

如果改写为 return Tag.EVAL_BODY_INCLUDE 则输出标签体

如果改写为 return Tag.SKIP_BODY 则不输出标签体 

                                  doEndTag 方法默认是 return super.doEndTag();

如果改写为 return Tag.EVAL_PAGE 则输出

如果改写为 return Tag.SKIP_PAGE 则停止输出

 

假如需要标签体执行 5 次,在 doAfterBody 方法里写:

复制代码
@Override
public int doStartTag() throws JspException {
    return Tag.EVAL_BODY_INCLUDE;
}

@Override
public int doAfterBody() throws JspException {
    int x=5;
    x--;
    if(x>0){
        return IterationTag.EVAL_BODY_AGAIN;            
    }else{
        return IterationTag.SKIP_BODY;
    }
}
复制代码
复制代码
// 修改标签体
public class TagDemo4 extends BodyTagSupport {
    @Override
    public int doStartTag() throws JspException {
        return BodyTag.EVAL_BODY_BUFFERED;
    }

    @Override
    public int doEndTag() throws JspException {
        BodyContent bc = this.getBodyContent();
        String content = bc.getString();
        content = content.toUpperCase();

        try {
            this.pageContext.getOut().write(content);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        
        return Tag.EVAL_PAGE;
    }
}
复制代码

 

posted on   z5337  阅读(166)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示