JSP Custom Labels

Source: Internet
Author: User
Tags get ip tag name tld

Assuming that the current client's IP address is output to the browser, we can now write

<%//gets the IP address of the current user,   String ip=request.getremotehost ();   Out.print ("The IP address of the current user is:" +ip);   %>

But we now want to minimize Java code on the JSP page, this time we can learn the tag as before, we define a tag, by calling the tag to achieve the display client IP address.

The first step is to create a common Java class, inheriting the Simpletagsupport class, called the tag processor class (to handle our requirements, for example here, we use it to obtain IP, while printing processing), the code is as follows

Package Com.gqx.a_tag;import Java.io.ioexception;import Javax.servlet.http.httpservletrequest;import Javax.servlet.jsp.jspcontext;import Javax.servlet.jsp.jspexception;import Javax.servlet.jsp.jspwriter;import Javax.servlet.jsp.pagecontext;import javax.servlet.jsp.tagext.simpletagsupport;/** * Tag Processor class * @author Administrator * (1), Inherit Simpletagsupport * (2), cover Dotag method, Dotag No request method, we have no way to get the IP address; *class Simpletagsupport implemented Interfaces:jsptag, Simpletag, is sure to implement the method *simpletag inside the method has Setjspcontext (Jspcontext pc) This method, passed in Jspcontext * but class Jspcontext extended by Javax.servlet.jsp.JspContext Direct known subclasses:pagecontext * i.e. Jspcontext subclass is PageContext, Can be through polymorphic to strong, once we get the PageContext, we are equivalent to get the rest of the JSP eight built-in objects */public class Showiptag extends Simpletagsupport{private Jspcontext jspcontext;//Implement Setjspcontext method to get PageContext object public void Setjspcontext (Jspcontext pc) {this.jspcontext= PC;} @Overridepublic void Dotag () throws Jspexception, IOException {//Because Jspcontext is a subclass of PageContext, you can JspcontextUpward Transformation PageContext pagecontext= (PageContext) jspcontext;//through the PageContext to get the request (the same reason,  HttpServletRequest Subclass is Servletrequest//interface servletreques all known Subinterfaces:httpservletrequest HttpServletRequest request= (HttpServletRequest) pagecontext.getrequest (); String Ip=request.getremotehost (); JspWriter writer=pagecontext.getout (); Writer.write ("Get IP address using custom tag:" +ip);}}

We can follow the system jstl already have the tag tag, reference its original code, in the Web project Web-inf directory to create a TLD file (I am called Gqxtag.tld file) and then will be useless to delete, the remainder of the code is as follows

<?xml version= "1.0" encoding= "UTF-8"? ><taglib xmlns= "Http://java.sun.com/xml/ns/javaee"    xmlns:xsi= " Http://www.w3.org/2001/XMLSchema-instance "    xsi:schemalocation=" Http://java.sun.com/xml/ns/javaee/http Java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd "    version=" 2.1 ">     <!--Tag Library version---  < Tlib-version>1.2</tlib-version>  <!--Tag Library prefixes--  <short-name>c</short-name>  <!--The unique tag of the TLD file--  <uri>http://www.gqxing.com</uri>  <!--This is the label's declaration  -- <tag>    <!--tag name--    <name>showIp</name>    <!--full name of the tag processor class--    < Tag-class>com.gqx.a_tag. Showiptag</tag-class>    <!--output Content format-    <body-content>scriptless</body-content>  </tag>  </taglib>

When copying the path of the class label, we can go to the relevant class right click here, select Copy qualified Name to get the path of the related class processor

Then we can use it in the JSP page, first, as in the previous JSTL tag, we use the TAGLIB directive to declare

<% @taglib uri= "http://www.gqxing.com" prefix= "GQX"%>

Then directly in the body of the JSP to call the tag directly

<gqx:showIp></gqx:showIp>

Results

And we're going to take a closer look at the source code of Simpletagsupport found the same codes as ours,

Private Jspcontext jspcontext;public void Setjspcontext (Jspcontext pc) {this.jspcontext=pc;}
Public Jspcontext Getjspcontext (Jspcontext pc) {return this.jspcontext;}

So we can simplify our code.

public class Showiptag extends simpletagsupport{@Overridepublic void Dotag () throws Jspexception, IOException {HTTPSERVL Etrequest request= (HttpServletRequest) pagecontext.getrequest (); String Ip=request.getremotehost (); JspWriter writer=pagecontext.getout (); Writer.write ("Get IP address using custom tag:" +ip);}}
How to perform a custom label

First, when the server starts, load each Web app and load all the files under each web-info, such as Web. XML, and a usertag.tld file that I just defined.

(1), the server accesses the http://localhost:8080/JspDemo/usertag/demo1.jsp resource file, translates the JSP file into a Java file, and continues to compile into a class file, invoking the life cycle of the Jsp_service () method.

(2) Check the JSP file through the TAGLIB directive declaration of the TLD file, whether there is a TLD file named Http://www.gqxing.com, no error, there will be read the file, at the same time into memory.

(3), when the JSP bytecode read <gqx:showIp> This tag, will go to the above TLD file to find, while reading <tag-class>com.gqx.a_tag. Showiptag</tag-class>, and then constructs the Showiptag object, then calls inside the method.

Customizing the life cycle of label processor classes

When I wrote the custom label class just now, I inherited the Simpletag interface, and now we can look at the method of the interface.

The sequence described below is the life cycle of the Simpletag

void Setjspcontext (Jspcontext pc)

Sets the PageContext object, passing in the PageContext (a certain call) to get the PageContext object through the Getjspcotext () method

void SetParent (Jsptag parent) Sets the parent tag object, passes in the parent label object, and does not call this method if there is no parent tag. Gets the parent tag object through the GetParent () method.
void Setxxx (value) Setting property values
void Setjspbody (Jspfragment jspbody)

Sets the contents of the label body. The tag body content is encapsulated in the jspfragment pair image and then passed in to the Jspfragment object.

The contents of the label body are obtained by Getjspbody () method. If there is no label body content, this method is not called

void Dotag () The method that is called when the label is executed. (must be called)

In order to better understand, now open the translated Demo1_jsp.java source file, found in the method of Jsp_service () in addition to the JSP page outward output method, found that contains a method

    ...//Output statement      out.write ("   \ t");    if (_jspx_meth_gqx_005fshowip_005f0 (_jspx_page_context))     return;    Out.write ("\ r \ n"); ...//Output statement  

The details of the method are then found at the bottom of the file, as follows

Incoming Pagecontext,pagecontext can get the remaining eight built-in objects  private Boolean _jspx_meth_gqx_005fshowip_005f0 (PageContext _jspx_ Page_context)          throws Throwable {    PageContext pagecontext = _jspx_page_context;    JspWriter out = _jspx_page_context.getout ();  Gqx:showip instantiates the object (the class previously defined)    Com.gqx.a_tag. Showiptag _jspx_th_gqx_005fshowip_005f0 = new Com.gqx.a_tag. Showiptag ();    Org.apache.jasper.runtime.AnnotationHelper.postConstruct (_jsp_annotationprocessor, _jspx_th_gqx_005fshowip_ 005F0);    As seen earlier in the Simpletag method there is a Setjspcontext method to encapsulate, then in other methods can be Getjspcontext method to obtain the object    _jspx_th_gqx_005fshowip_ 005f0.setjspcontext (_jspx_page_context);    Is the Dotag method that we overwrite    _jspx_th_gqx_005fshowip_005f0.dotag ();    Org.apache.jasper.runtime.AnnotationHelper.preDestroy (_jsp_annotationprocessor, _jspx_th_gqx_005fshowip_005f0);    return false;  }}

The above code we do not use the Setjspbody method, this time, can be in the original JSP page to add tag content

<gqx:showIp>gqx</gqx:showIp>

We will find that the above code has changed, adding the Setjspbody method to it.

Tag content through the Help package, by Setjspbody incoming, in the same way, can be obtained by the Get method, and then in the class to do the related processing    _jspx_th_gqx_005fshowip_005f0.setjspbody ( New Demo1_jsphelper (0, _jspx_page_context, _jspx_th_gqx_005fshowip_005f0, null));

  

JSP Custom Labels

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.