自定义类:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
public class CalcTag extends TagSupport {
private int numA;
private int numB;
public int getNumA() {
return numA;
}
public void setNumA(int numA) {
this.numA = numA;
}
public int getNumB() {
return numB;
}
public void setNumB(int numB) {
this.numB = numB;
}
@Override
public int doStartTag() throws JspException {
ServletResponse sr= super.pageContext.getResponse();
try {
PrintWriter out=sr.getWriter();
out.println("<h1>");
out.print(numA);
out.print("+");
out.print(numB);
out.print("=");
out.println(numA+numB);
out.println("</h1>");
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return SKIP_BODY;
}
}
创建后缀为tld的文件:
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" xmlns="http://Java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd">
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>Example TLD with Body</short-name>
<tag>
<name>calc</name>
<tag-class>com.wisezone.tag.CalcTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>numA</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>numB</name>//变量名首字母不能大写
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
web.xml中配置注册:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>tagweb</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<!-- 注册 -->
<jsp-config>
<taglib>
<taglib-uri>/wisezone</taglib-uri>
<taglib-location>/WEB-INF/mytag.tld</taglib-location>
</taglib>
</jsp-config>
</web-app>
jsp页面使用:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="/wisezone" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<c:calc numB="${5+3 }"numA="${8+2 }"/>
</body>
</html>