1.导入架包
<!--javaee-->
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
2.新建标签类
com.util.MyTay
继承 SimpleTagSupport
public class MyTag extends SimpleTagSupport {
@Override //定义希望标签做的事情
public void doTag() throws JspException, IOException {
JspWriter out= this.getJspContext().getOut();
out.print("这是我的自定义标签");
}
}
3.在WEB-INF文件夹下创建mytag.tld
<?xml version="1.0" encoding="UTF-8" ?>
<taglib>
<tlib-version>1.1</tlib-version>
<jsp-version>2.0</jsp-version>
<!--默认的简称-->
<short-name>mytag</short-name>
<!--引用地址-->
<uri>http://java.sun.com/jsp/mytag/my</uri>
<tag>
<name>abc</name>
<tag-class>com.util.MyTag</tag-class>
<!--写入内容为空-->
<body-content>empty</body-content>
可以写入,二者只能选一个
<body-content>scriptless</body-content>
</tag>
</taglib>
4.jsp
empty属性,则标签中间不能写东西
中间不能写东西,不然会报错
<mytag:acb>不能写<mytag:acb/>
读取标签中间的内容
更改MyTag的内容为
public class MyTag extends SimpleTagSupport {
@Override //定义希望标签做的事情
public void doTag() throws JspException, IOException {
//获得标签对中间的内容并输出
StringWriter sw=new StringWriter();
this.getJspBody().invoke(sw);
this.getJspContext().getOut().print(sw);
}
}
在标签里面添加属性
比如 <c:if test="">中的test
在mytag.tld文件添加
<?xml version="1.0" encoding="UTF-8" ?>
<taglib>
<tlib-version>1.1</tlib-version>
<jsp-version>2.0</jsp-version>
<!--默认的简称-->
<short-name>mytag</short-name>
<!--引用地址-->
<uri>http://java.sun.com/jsp/mytag/my</uri>
<tag>
<name>abc</name>
<tag-class>com.util.MyTag</tag-class>
<!--写入内容为空-->
<body-content>empty</body-content>
可以写入,二者只能选一个
<body-content>scriptless</body-content>
</tag>
</taglib>
----------------------------------------------------
.jsp
<mytag:acb/> 中间不能写东西,不然会报错
-----------------------------------------------------
标签中间的内容读到标签
public class MyTag extends SimpleTagSupport {
@Override //定义希望标签做的事情
public void doTag() throws JspException, IOException {
//获得标签对中间的内容并输出
StringWriter sw=new StringWriter();
this.getJspBody().invoke(sw);
this.getJspContext().getOut().print(sw);
}
}
----------------------------------------------------------
在标签里面添加属性,比如<c:if test="">
在mytag.tld文件添加
<?xml version="1.0" encoding="UTF-8" ?>
<taglib>
<tlib-version>1.1</tlib-version>
<jsp-version>2.0</jsp-version>
<!--默认的简称-->
<short-name>mytag</short-name>
<!--引用地址-->
<uri>http://java.sun.com/jsp/mytag/my</uri>
<tag>
<name>abc</name>
<tag-class>com.util.MyTag</tag-class>
<!--写入内容为空-->
<!--<body-content>empty</body-content>-->
<body-content>scriptless</body-content>
<attribute>
<!--属性的名称-->
<name>test</name>
<!--属性是否必须要写-->
<required>true</required>
<!--内容的属性-->
<type>java.lang.String</type>
<rtexprvalue>true</rtexprvalue><!--支持el表达式解析-->
</attribute>
</tag>
</taglib>
在MyTag添加
private String test;
//生成get和set方法
public void setTest(){
********
}
public String getest(){
*********
}
this.getJspContext().getOut().print(test+".....");