jsp自定义标签

自定义标签的实现由两部分组成:标签库描述文件、标签处理类;

1.在WEB-INF目录下创建name.tld文件即标签库描述文件:

<?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 web-jsptaglibrary_2_0.xsd"
	version="2.0">
	<tlib-version>1.0</tlib-version>
	<short-name>mytaglib</short-name>
	<!-- 定义该标签库的URI 必须可以空-->
	<uri></uri>
	<!-- 定义第一个标签 -->
	<tag>
		<!-- 定义标签名 -->
		<name>field</name>
		<!-- 定义标签处理类 -->
		<tag-class>org.lxh.taglib.FieldTag</tag-class>
		<!-- 定义标签体为空 -->
		<body-content>empty</body-content>
		<attribute>
			<name>field</name>
			<required>true</required> 
			<rtexprvalue>true</rtexprvalue>
		</attribute>
		<attribute>
			<name>count</name>
			<rtexprvalue>true</rtexprvalue>
			<retuired>true</retuired>
		</attribute>
	</tag>
</taglib>

2.编写tag对应的class类即标签处理类

public class FieldTag extends TagSupport {
	private static final long serialVersionUID = -3282476920723218742L;
	private String field;
	private Integer count;

	public final String getField() {
		return field;
	}

	public final void setField(String field) {
		this.field = field;
	}
	
	public final Integer getCount() {
		return count;
	}

	public final void setCount(Integer count) {
		this.count = count;
	}

	@Override
	public int doEndTag() throws JspException {

		try {
			JspWriter out = pageContext.getOut();
			out.print(field);
			out.print(count);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return super.doEndTag();
	}
}
jsp引用:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="tf" uri="/WEB-INF/tld/testfield.tld" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
	Integer a = 10;
%>
<tf:field field="hi" count="<%=a%>"/>
</body>
</html>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值