自定义标签库
一:tld文件编写(tld文件放置在webapp/WEB-INF/)
<?xml version="1.0" encoding="UTF-8" ?> <taglib 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" version="2.0"> <description>JSTL 1.1 core library</description> <display-name>JSTL core</display-name> <tlib-version>1.1</tlib-version> <short-name>zhb</short-name> <uri>http://www.zhb.cn/mytag</uri> <!-- 显示IP地址 --> <tag> <description> Catches any Throwable that occurs in its body and optionally exposes it. </description> <name>viewIP</name> <tag-class>MyTag</tag-class> <body-content>empty</body-content> </tag> </taglib>
二:自定义文件的依赖类编写
import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.TagSupport; import com.sun.org.apache.xml.internal.resolver.helpers.PublicId; public class MyTag extends TagSupport{ private static final long serialVersionUID = 1L; @Override public int doStartTag() throws JspException { //内置一个pageContext对象,我们之前说到pageContext对象,它里面是封装了9个隐式对象 HttpServletRequest request = (HttpServletRequest)this.pageContext.getRequest(); JspWriter out = this.pageContext.getOut(); String ip = request.getRemoteAddr(); try { out.print(ip); } catch (IOException e) { throw new RuntimeException(e); } return TagSupport.EVAL_PAGE; } @Override public int doEndTag() throws JspException { return TagSupport.EVAL_PAGE; } }