Struts 1.2 自定义标签步骤如下:
1. tld 定义 :xx-security.tld
2. 写支持tag的java class : PasswordTag.java, 一般继承自 TagSupport (WriteTag 等)
3. (optional)在web.xml中配置标签库加载 1中的tag
4. 调用自定义标签的html
1. xx-security.tld 如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>xx-security</short-name>
<description>
<![CDATA[
<p>
This taglib contains tags used for some security features of xx.
</p>
]]>
</description>
<tag>
<name>applet-param</name>
<tag-class>com.company.proj.web.taglib.security.ParamTag</tag-class>
<body-content>empty</body-content>
<description><![CDATA[
<p><strong></strong></p>
]]>
</description>
<attribute>
<name>name</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<description></description>
</attribute>
<attribute>
<name>value</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<description></description>
</attribute>
</tag>
<tag>
<name>password</name>
<tag-class>com.company.proj.web.taglib.security.PasswordTag</tag-class>
<body-content>empty</body-content>
<description>
<![CDATA[
<p><strong></strong></p>
]]>
</description>
</tag>
</taglib>
Note: 没有什么注意,只要按照格式写就好
2. 支持tag的PasswordTag.java
import java.io.IOException;
import java.io.Writer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class PasswordTag extends TagSupport {
private static final long serialVersionUID = 3174234039143531079L;
@Override
public int doStartTag() throws JspException {
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
Writer out = pageContext.getOut();
try {
out.write("<input type=\"password\" size=\"20\" class=\"inputBox\" name=\"");
out.write("password");
out.write("\" value=\"");
out.write("\">\r\n");
out.flush();
} catch (IOException ex) {
throw new JspTagException("Error lahh");
}
return EVAL_BODY_INCLUDE;
}
@Override
public int doEndTag() throws JspException {
// Writer out = pageContext.getOut();
// try {
// out.write("\r\n");
// out.write("Hello World,snow365bbb!");
//
// } catch (IOException ex) {
// throw new JspTagException("Error lahh");
// }
// pageContext.getSession().setAttribute("xx", XX);
return EVAL_PAGE;
}
}
Note: 1)根据需要,重写doStartTag() doEndTag()
2) pageContext.getOut().write()就是在页面输出html语言
3. 在web.xml中配置标签库加载。(这个不做,也没有问题,jsp 里面uri已经写明)
<taglib>
<taglib-uri>/WEB-INF/tld/xx-security.tld</taglib-uri>
<taglib-location>/WEB-INF/tld/xx-security.tld</taglib-location>
</taglib>
4.页面调用
<%@ taglib uri="/WEB-INF/tld/xx-security.tld" prefix="xx-security"%>
<xx-security:password></xx-security:password>