空标签
需要集成TagSupport类,并覆写doStartTage方法
package com.ming.TagDome;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class HelloTag extends TagSupport {
@Override
public int doStartTag() throws JspException {
// 获得输出流对象
JspWriter out = super.pageContext.getOut();
try{
out.println("hello world
");
}catch (Exception e){
e.printStackTrace();
}
// 没有便签体
return TagSupport.SKIP_BODY;
}
}
然后需要再次定义标签描述文件,即web-inf文件下的helloTage.tld文件
1.0
firsttag
hello
com.ming.TagDome.HelloTag
empty
最后,在页面引入相关内容
<%--
Created by IntelliJ IDEA.
User: ming
Date: 19-3-20
Time: 下午10:01
To change this template use File | Settings | File Templates.
--%>
<%@ page cOntentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="myTag" uri="/WEB-INF/hellotag.tld"%>
进行文件映射
在web.xml文件中对所有的tld文件进行映射.
Archetype Created Web Application
hello_tag
/WEB-INF/hellotag.tld
DB Connection
jdbc/ming
javax.sql.DataSource
Container
运行原理 访问的时候,如果遇到标签,则会根据uri去寻找对应的配置文件,根据配置文件,读取相应的标签类class,然后,进行输出
定义有属性的标签
一个栗子,格式化日期标签类
package com.ming.TagDome;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTag extends TagSupport {
// 接收魔板
private String format;
@Override
public int doStartTag() throws JspException {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(this.format);
try{
// 输出格式化后的日期
super.pageContext.getOut().write(simpleDateFormat.format(new Date()));
}catch (IOException e){
e.printStackTrace();
}
return TagSupport.SKIP_BODY;
}
public String getFormat(){
return format;
}
public void setFormat(String _format){
this.format = _format;
}
}
1.0
datetag
date
com.ming.TagDome.DateTag
empty
format
true
true
<%--
Created by IntelliJ IDEA.
User: ming
Date: 19-3-20
Time: 下午10:01
To change this template use File | Settings | File Templates.
--%>
<%@ page cOntentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="myTag" uri="ming_date"%>
在设置标签属性的时候,属性为format的时候,会自动调用set方法进行赋值
剩下的大概也没啥了.就是继承一些接口,一些类即可,感觉和微信小程序的模板类似.