1: 编写一个实现Tag接口的Java类(标签处理器类)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 |
package
cn.gbx.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.tagext.TagSupport; public
class
ViewIpTag 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) { throw
new
RuntimeException(e); } return
super .doStartTag(); } } |
2:在tld文件中对标签处理器类进行描述 tld文件的位置放在WEB-INF中(/Test2/WebRoot/WEB-INF/jsptag/gbx.tld)。 文件模式可以从tomcat中查看
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 |
<?xml version= "1.0"
encoding= "UTF-8"
?> <taglib xmlns= "http://java.sun.com/xml/ns/j2ee" 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>http: //www.gbx.com.cn</uri> <tag> <description>show client IP</description> <!-- 注释说明 --> <name>viewIP</name> <!-- 配置的标签名 --> <tag- class >cn.gbx.web.tag.ViewIpTag</tag- class > <body-content>empty</body-content> <!-- 标签体为空 --> </tag> </taglib> |
3:在jsp页面利用taglib指令导入我们的tld文件的uri, 然后使用即可。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29 |
<%@ page language= "java"
import = "java.util.*"
pageEncoding= "ISO-8859-1" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+ "://" +request.getServerName()+ ":" +request.getServerPort()+path+ "/" ; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" > <html> <head> <base href= "<%=basePath%>" > <title>My JSP ‘1.jsp‘
starting page</title> <meta http-equiv= "pragma"
content= "no-cache" > <meta http-equiv= "cache-control"
content= "no-cache" > <meta http-equiv= "expires"
content= "0" > <meta http-equiv= "keywords"
content= "keyword1,keyword2,keyword3" > <meta http-equiv= "description"
content= "This is my page" > <!-- <link rel= "stylesheet"
type= "text/css"
href= "styles.css" > --> </head> <body> <gbx:viewIP/> </body> </html> |
原文:http://www.cnblogs.com/E-star/p/3521601.html