java代码:
package com.zx.tag;
import java.io.IOException;
import java.io.StringWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class IfTag extends SimpleTagSupport {
//1.获取属性名为test的属性值
/*
* (自定义标签类没有提供给我们属性值的获取方法)
* 我们需要将属性名封装成成员变量(SimpleTagSupport会通过对应成员变量的
* set方法将页面的属性值注入到这个成员变量中)
*/
private boolean test;
public void setAbc(boolean test) {
this.test = test;
}
@Override
public void doTag() throws JspException, IOException {
//2.判断属性值是否为true
if(test) {
//3.根据判断结果决定是否显示标签体的内容
StringWriter sw = new StringWriter();
this.getJspBody().invoke(sw);
this.getJspContext().getOut().write(sw.toString());
}
}
}
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 http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>自定义标签</description>
<display-name>zdytag</display-name>
<tlib-version>1.0</tlib-version>
<!-- zy:ip -->
<short-name>zy</short-name>
<uri>http://www.zhuoxun/jxb</uri>
<tag>
<description>这个标签用来将标签体的内容小写改大写</description>
<name>if</name>
<tag-class>com.zx.tag.IfTag</tag-class>
<body-content>scriptless</body-content>
<!-- 对参数进行注册 -->
<attribute>
<description>条件判断</description>
<name>abc</name>
<!-- 这个参数是否为必须参数(此标签必须有这个参数,否则报错) -->
<required>true</required>
<!-- runtime expresstion value(是否支持el表达式) -->
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
html代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.zhuoxun/jxb" prefix="zy"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>main</title>
</head>
<body>
<%
request.setAttribute("address", "TianJin");
String address = "TianJin";
request.setAttribute("sex", "man");
%>
<!-- jsp表达式 -->
<!-- 自定义标签模拟c:if -->
<!-- (有标签体有参有返回值) -->
<!-- 目的是获取属性名为abc的属性值,然后做判断,然后决定是否显示标签体的内容 -->
性别:
<zy:if abc="${sex=='man' }">
男
</zy:if>
</body>
</html>
其他
自己建立了一个技术群,大家愿意主动学习和分享,愿意一块实现一些有意思的技术,进行理论和实践的交流。这里面有前端和后段,不是单一的一种,方便大家沟通前后端兼容问题