java编写自定义标签
java实现自定义标签需要继承extends javax.servlet.jsp.tagext.TagSupport类。
编写第一个自定义标签,包括两个文本框
package tag;
import java.io.IOException;
import javax.servlet.jsp.JspException;
public class firsetTag extends javax.servlet.jsp.tagext.TagSupport {
??? private String t1;
??? private String t2;
???
??? public String getT1() {
??? ??? return t1;
??? }
??? public void setT1(String t1) {
??? ??? this.t1 = t1;
??? }
??? public String getT2() {
??? ??? return t2;
??? }
??? public void setT2(String t2) {
??? ??? this.t2 = t2;
??? }
??? @Override
??? public int doStartTag() throws JspException {
??? ??? // TODO Auto-generated method stub
??? ??? String sHtml="<input type=\"text\" value=\""+this.getT1()+"\">";
??? ??? sHtml+="<input type=\"text\" value=\""+this.getT2()+"\">";
??????? try
??????? {
??? ??? ?? this.pageContext.getOut().write(sHtml);
??????? }catch(IOException ex)
??????? {
??????? ??? throw new JspException(ex.getMessage());
??????? }
??? ??? return this.EVAL_PAGE;?? //继续执行
??? }
}
?
编写自定义标签的配置文件,MyXml.xml
<?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>2.2.3</tlib-version>
?? <jsp-version>1.2</jsp-version>
?? <short-name>wangfu Common Taglib</short-name>
?? <uri>/wangfu</uri>
?? <tag>
?? <name>firsetTag</name>
??????? <tag-class>tag.firsetTag</tag-class>
??????? <body-content>empty</body-content>
??????? <attribute>
?????????? <name>t1</name>
?????????? <required>true</required>
?????????? <rtexprvalue>true</rtexprvalue>
??????? </attribute>
?? </tag>???
</taglib>
?
在web.xml中的配置
?<jsp-config>
??? ??? <taglib>
??? ???????? <taglib-uri>/th</taglib-uri>
??? ???????? <taglib-location>/WEB-INF/tlds/MyXml.xml</taglib-location>
??? ??? </taglib>
???? </jsp-config>
?
在jsp里面中使用:
<%@ taglib prefix="wangfu" uri="/th" %>
<body>
??? <form action="" method="post">
??????? <wangfu:firsetTag t1="wangfu"/>
??? </form>
? </body>
?
?