1、编写一个实现tag接口的java类,并覆盖其doStarttag方法
public class ViewIpTag implements Tag {
private PageContext pagecontext;
public void setPageContext(PageContext arg0) {
this.pagecontext = arg0;
}
public int doStartTag() throws JspException {
HttpServletRequest request = (HttpServletRequest) this.pagecontext.getRequest();
JspWriter out = this.pagecontext.getOut();
String ip = request.getRemoteAddr();
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 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>My JSP '1.jsp' starting page</title>
</head>
<body>
您的IP是:<itcast:viewIp/>
</body>
</html>