1. Compile a tag processor class that implements the tag Interface
Copy codeThe Code is as follows: package cn. itcast. 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. PageContext;
Import javax. servlet. jsp. tagext. Tag;
Public class ViewIPTag implements Tag {
Private PageContext pageContext;
Public int doStartTag () throws JspException {
HttpServletRequest request = (HttpServletRequest) pageContext. getRequest (); // obtain the request and out objects in the Servlet on the page
JspWriter out = pageContext. getOut ();
String ip = request. getRemoteAddr (); // obtain the user ip Address
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 setPageContext (PageContext arg0 ){
This. pageContext = arg0; // PageContext obtains objects such as user request out.
}
Public void setParent (Tag arg0 ){
}
}
2. Create a tld file in the web-inf/directory and describe the tag processor in the tld file.
Copy codeThe Code is as follows: <? 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> <! -- Configure a tag name for the tag processor class -->
<Tag-class> cn. itcast. web. tag. ViewIPTag </tag-class>
<Body-content> empty </body-content>
</Tag>
</Taglib>
3. import and use custom tags on the jsp page
Copy codeThe Code is as follows: <% @ 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> IP address of the output client </title>
</Head>
<Body>
Your IP address is: <itcast: viewIP/>
</Body>
</Html>