JSP自定义标签获取用户IP地址的方法
1、编写一个实现tag接口的标签处理器类
package cn.itcast.web.tag;
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.tag;
public class viewiptag implements tag {
private pagecontext pagecontext;
public int dostarttag() throws jspexception {
httpservletrequest request = (httpservletrequest) pagecontext.getrequest();//获取页面servlet中 request 和out 对象
jspwriter out = pagecontext.getout();
string ip = request.getremoteaddr(); //获取用户ip地址
try {
out.write(ip);
} catch (ioexception e) {
throw new runtimeexception(e);
}
return 0;
}
public int doendtag() throws jspexception {
return 0;
}
public tag getparent() {
return null;
}
public void release() {
}
public void setpagecontext(pagecontext arg0) {
this.pagecontext = arg0;//pagecontext获取用户request out 等对象
}
public void setparent(tag arg0) {
}
}
2、在web-inf/目录下新建tld文件,在tld文件中对标签处理器进行描述
<?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 http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>a tag library exercising simpletag handlers.</description>
<tlib-version>1.0</tlib-version>
<short-name>simpletaglibrary</short-name>
<uri>/itcast</uri>
<tag>
<name>viewip</name> <!-- 为标签处理器类配一个标签名 -->
<tag-class>cn.itcast.web.tag.viewiptag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
3、在jsp页面中导入并使用自定义标签
<%@ page language="java" import="java.util.*" pageencoding="utf-8"%>
<%@taglib uri="/itcast" prefix="itcast" %>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en">
<html>
<head>
<title>输出客户机的ip</title>
</head>
<body>
您的ip是:<itcast:viewip/>
</body>
</html>
上一篇: 关于jsp页面使用jstl的异常分析