java代码:
package com.zx.tag;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
/**
* 定义了一个自定义标签
* @author zhangyi
*
*/
public class IpTag extends SimpleTagSupport{
/**
* 当调用这个标签时执行的方法
*/
@Override
public void doTag() throws JspException, IOException {
//要获取请求和响应对象
PageContext pc = (PageContext)getJspContext();
String addr = pc.getRequest().getLocalAddr();
System.out.println("ip="+addr);
pc.getOut().write(addr);
}
}
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>自定义标签</description>
<display-name>zdytag</display-name>
<tlib-version>1.0</tlib-version>
<!-- zy:ip -->
<short-name>zy</short-name>
<uri>http://www.zhuoxun/jxb</uri>
<tag>
<description>这个标签用来获取当前登录用户的ip地址</description>
<name>ip</name>
<tag-class>com.zx.tag.IpTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
html页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://www.zhuoxun/jxb" prefix="zy"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>main</title>
</head>
<body>
<!-- jsp表达式 -->
当前访问用户的ip:
<%=request.getLocalAddr()%><br>
<!-- 自定义标签(无参有返回值) -->
当前访问用户的ip:<zy:ip/>
</body>
</html>
共同探讨学习技术创建技术氛围Day9884125