自定义JSTL标签(属性&标签体)

版权声明:本博主所有播客均为原创作品,如有商业用途,抄袭等,必追究其法律程序。 https://blog.csdn.net/wangzijian121/article/details/86086940

自定义带属性和标签体的标签,结构为:java–tld–jsp

MyTag4.java

package cn.wang.tag;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;

public class MyTag4 extends SimpleTagSupport {

	private boolean test;

	/*
	 * 这个方法由tomcat调用,在doTag()之前
	 */
	public void setTest(boolean test) {
		this.test = test;
	}

	@Override
	public void doTag() throws JspException, IOException {
		if (test) {
			this.getJspBody().invoke(null);//如果test为真,则输出标签体内容
		}
	}
}

wang.cn.tld

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" 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">
	<tlib-version>1.0</tlib-version>
	<short-name>wang</short-name>
	<tag>
		<name>MyTag4</name>
		<!-- java文件的路径 -->
		<tag-class>cn.wang.tag.MyTag4</tag-class>
		<!--标签体的类型(html&el) -->
		<body-content>scriptless</body-content>
		<attribute>
			<!-- 属性的名称 -->
			<name>test</name>
			<!-- 是否为必填 -->
			<required>true</required>
			<!--是否支持el表达式,一般为true -->
			<rtexprvalue>true</rtexprvalue>
		</attribute>
	</tag>
</taglib>

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@taglib prefix="wang" uri="/WEB-INF/tlds/wang.cn.tld"%>
<%
	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>自定义标签</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">
</head>
<body>
	<wang:MyTag4 test="${1==1}">执行了标签体</wang:MyTag4>
</body>
</html>

知识补充:在自定义标签中中断可使用: throw new SkipPageException();
底层的servlet并不抛出该异常,在catch中对该异常进行了单独的 处理,实现后面的所有标签全不执行,如图。在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/wangzijian121/article/details/86086940
今日推荐