简单自定义标签步骤

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

使用自定义标签移除jsp页面中的java代码,只需要完成以下两个步骤:
编写一个实现Tag接口的Java类(标签处理器类)。
编写标签库描述符(tld)文件,在tld文件中对标签处理器类进行描述。

1: 编写一个实现Tag接口的Java(标签处理器类)

package cn.gbx.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();
		try {
			out.print(request.getRemoteAddr());
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return super.doStartTag();
	}
	
}

  

2:在tld文件中对标签处理器类进行描述 tld文件的位置放在WEB-INF中(/Test2/WebRoot/WEB-INF/jsptag/gbx.tld)。  文件模式可以从tomcat中查看

<?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">
    <description>A tag library exercising SimpleTag handlers.</description>
    <tlib-version>1.0</tlib-version>
    <short-name>SimpleTagLibrary</short-name>
    <uri>http://www.gbx.com.cn</uri>
    
    <tag>
        <description>show client IP</description>  <!-- 注释说明 -->
        <name>viewIP</name>  <!-- 配置的标签名 -->
        <tag-class>cn.gbx.web.tag.ViewIpTag</tag-class>
        <body-content>empty</body-content> <!-- 标签体为空 -->
    </tag>
    
</taglib>

  

3:在jsp页面利用taglib指令导入我们的tld文件的uri, 然后使用即可。

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.gbx.com.cn" prefix="gbx" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP '1.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    <gbx:viewIP/>
  </body>
</html>

  

原文地址:https://www.cnblogs.com/E-star/p/3521601.html