在JavaWeb开发中,为了代码的整洁和和统一,常在JSP中用标签来实现显示页面;而不是直接嵌入Java代码。除了内置标签和JSTL标签库外,在开发过程中用户也可以根据需要自定义一些标签。下面总结一下自定义标签的简要步骤:
这里以JSP界面里显示一个登录框为例来说明,即自定义一个标签显示登录框。
一、新建一个Web项目后,定义一个类,继承SimpleTagSupport类;并覆盖doTag()方法。
public class LoginTag extends SimpleTagSupport {
//标签处理程序
public void doTag() throws IOException{
PageContext pageContext=(PageContext)this.getJspContext();
String html="";
html+="<table>";
html+="<tr>";
html+="<td>用户名:</td><td><input type='text' name='"+pageContext.getAttribute("user",pageContext.PAGE_SCOPE)+"'/></td>";
html+="</tr>";
html+="<tr>";
html+="<td>密码:</td><td><input type='password' name='"+pageContext.getAttribute("pwd",pageContext.PAGE_SCOPE)+"'/></td>";
html+="</tr>";
html+="<tr>";
html+="<td><input type='submit' name='sub' value='登录'/></td><td><input type='reset' name='res' value='重置'/></td>";
html+="</tr>";
html+="</table>";
JspWriter out=(JspWriter)pageContext.getOut();
out.write(html);
}
}
二、在WEB-INF目录下,写一个.tld文件;用于指定标签处理器类的位置。(注:.tld一定要放到WEB-INF目录下,否则会出错。)
<?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">
<!-- 标签库的版本 -->
<tlib-version>1.1</tlib-version>
<!-- 标签库前缀 -->
<short-name>mtag</short-name>
<!-- tld文件的唯一标记,用于标识tld文件 -->
<uri>http://iot.hpu.zmm</uri>
<!-- 一个标签的声明 -->
<tag>
<!-- 标签名称 -->
<name>Login</name>
<!-- 标签处理器类的全名 -->
<tag-class>iot.hpu.zmm.LoginTag</tag-class>
<!-- 输出标签体内容格式 -->
<body-content>scriptless</body-content>
</tag>
</taglib>
三、在JSP页面头部导入自定义标签库
<%@taglib uri="http://iot.hpu.zmm" prefix="mtag" %>
其中,uri要与tld文件中的uri保持一致;prefix就是标签库的缩写。
四、使用自定义标签
<form action="#" method='post'>
<mtag:Login></mtag:Login>
</form>
大功告成,也就四步!!!