1.java类,使用简单标签,jsp2.0规范, 继承 SimpleTagSupport
public class ViewIpSimpleTag extends SimpleTagSupport {
@Override
public void doTag() throws JspException, IOException {
PageContext pageContext = (PageContext) this.getJspContext();
String ip = ((HttpServletRequest) pageContext.getRequest()).getRemoteAddr(); pageContext.getOut().write(ip);
}
}
1.java类,使用传统标签 jsp1.0, 继承 TagSupport(弃用)
/**
* jsp 自定义标签的步骤:
* 1.写一个类实现Tag接口(继承TagSupport类)
* 2.在WEB-INF文件夹中新建一个tld文件
* 3.在jsp 页面中导入taglib标签库,然后调用
*
*/
public class ViewIp extends TagSupport {
@Override
public int doStartTag() throws JspException {
try {
HttpServletRequest request = (HttpServletRequest) this.pageContext
.getRequest();
JspWriter out = this.pageContext.getOut();
String ip = request.getRemoteAddr();
out.print(ip);
} catch (IOException e) {
e.printStackTrace();
}
return super.doStartTag();
} }
2.tld文件(/webProjectName/WEB-INF/web.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">
<tlib-version>1.0</tlib-version>
<short-name>web</short-name>
<uri>www.bvb.de</uri> <tag>
<name>viewIp</name>
<tag-class>de.bvb.web.tag.ViewIpSimpleTag</tag-class>
<body-content>empty</body-content>
</tag> </taglib>
3.jsp页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!-- 3.1导入标签库 prefix和文件名一致,uri和.tld文件夹中的uri一致,uri也可以写为 uri="/WEB-INF/web.tld" -->
<%@ taglib prefix="web" uri="www.bvb.de"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> 你的ip是:
<!--3.2 使用自定义标签 -->
<web:viewIp /> 不使用自定义标签
<%
String ip = request.getRemoteAddr();
out.print(ip);
%> </head>
<body></body>