1 写一个标签处理类
//标签处理类
public class IpTag implements SimpleTag {
private PageContext pageContext;
//Web容器调用NO1
public void setJspContext(JspContext pc) {
System.out.println("setJspContext()");
pageContext = (PageContext) pc;
}
//Web容器调用NO2
public void doTag() throws JspException, IOException {
System.out.println("doTag()");
//取得HttpServletRequest请求对象
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
//取得客户端的IP地址
String ip = request.getRemoteAddr();
//取得out(JspWriter)对象
JspWriter out = pageContext.getOut();
//向浏览器输出
out.write(""+ip+"");
}
...
}
2 在/WEB-INF/目录下,写一个*.tld文件,目的是让Web容器知道自定义标签和标签处理类的对应关系
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
1.0
simple
http://java.sun.com/jsp/jstl/simple
ip
cn.itcast.web.jsp.tag.IpTag
empty
3 在JSP页面中,通过指令引用标签库
客户端IP为:
4 部署web应用,访问simple.jsp即可