看原来代码的是看见自定义标签,脑袋都没什么印象啦,赶紧记下。
定义一个类继承SimpleTagSupport,实现doTag()方法即可:
package servlet;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import Entity.User;
public class MyTag2 extends SimpleTagSupport{
public void doTag()throws JspException,IOException{
PageContext pctx=(PageContext)getJspContext();
//得到输出流
JspWriter out=pctx.getOut();
Date date=new Date(); //在页面输出当前时间
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
String dstr=sdf.format(date);
out.println(dstr);
}
}
当然,还必须给出自定义标签的 .tld文件,就像我们的 c 标签一样,内容直接复制c.tld文件即可,然后把相应内容替换掉:
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
version="2.1">
<description>JSTL 1.2 core library</description>
<display-name>JSTL core</display-name>
<tlib-version>1.2</tlib-version>
<short-name>kyle</short-name>
<uri>http://kyle1970/mytag</uri>
<tag>
<name>showTime</name>
<tag-class>servlet.MyTag2</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
short-name 表示我们的标签名; uri 表示该标签的唯一标示 ; tag中name表示使用的名字。
前端使用即:<kyle:showTime/>