1. 编写一个实现tag接口的java类
其中方法重写到doStartTag方法里
public class Tag1 extends TagSupport{
@Override
public int doStartTag() throws JspException {
HttpServletRequest request = (HttpServletRequest) this.pageContext.getRequest();
JspWriter out = this.pageContext.getOut();
try {
out.print(request.getRemoteAddr());
} catch (IOException e) {
e.printStackTrace();
}
return super.doStartTag();
}
}
2.写一个tld文件 放到WEB-INF下 这样
<?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>ys</short-name>
<uri>http://yangsheng.cn</uri>
在下面写tag信息
<tag>
<name>ViewIp</name>
<tag-class>cn.web.tag.Tag1</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
3. 用 taglib 引入标签 然后使用即可:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib uri="http://yangsheng.cn" prefix="ys" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP '1.jsp' starting page</title>
</head>
<body>
您的ip为:<ys:ViewIp/>
</body>
</html>
这样 就可以将 jsp中的 java代码 完全去掉