Javaweb review article 8 how to create custom tags, javaweb Article 8

Source: Internet
Author: User
Tags switch case

Javaweb review article 8 how to create custom tags, javaweb Article 8

The use of custom tags in Java Web development is quite large. Today, let's take a look at how custom tags are implemented.

1: What is a label?

A tag is an XML element. A tag can be used to make JSP pages easy to use and reuse.

2: main interfaces of the tag library for custom tags and the inheritance implementation diagram of Classes

3: Step-by-Step custom Tag 3.1: Tag Interface

Let's first look at a tag <td> </td> which has the start tag and end tag, and a parent tag such as <tr>. What do we need to implement a simple tag?

First: start tag 2: end tag 3: Resource Release 3 methods, and parent tag, if we want to get the content on this JSP, we need a PageContext. Now we should be clear about the elements needed to implement a tag. OK. Let's see what the Tag interface has.

3.1.1: int doStartTag () throws JspException; this is the starting method for starting execution.

3.1.2: int doEndTag () throws JspException; this is the final method.

3.1.3: void release (); releases object Resources

3.1.4: void setPageContext (PageContext pc); set the context object of the current page

3.1.5: void setParent (Tag t); set the parent Tag

3.1.6: Tag getParent (); get parent Tag

Through the above introduction, we should know how to write a tag. Let's try it out.

Public class HelloTag implements Tag {private PageContext pageContext; private Tag parent; public void setPageContext (PageContext pc) {this. pageContext = pc; // this method is called by the Implementation object of the jsp page} public void setParent (Tag t) {this. parent = t;} public Tag getParent () {return parent;} public int doStartTag () throws JspException {return SKIP_BODY;} public int doEndTag () throws JspException {// use pageContext to obtain the jspWriter object JspWriter out = pageContext. getOut (); try {// use JSPWriter to input information out to the client. print ("Hello Tag");} catch (IOException e) {e. printStackTrace () ;}return SKIP_PAGE;} public void release (){}

SKIP_BODY indicates that the content of the label body is ignored. Now that we have finished writing a label body, we will start to configure it.

Create a tlds folder in WEB-INFO, create a tld file, and set the following

<Tag> <name> hello </name> <tag-class> com. lp. tags. helloTag </tag-class> <body-content> empty </body-content> // indicates that the tag has no content. </tag>

Then we create a jsp file and add the Taglib command element <% @ taglib uri = "/WEB-INF/tlds/CustomTaglib. tld" prefix = "hello" %> In the jsp file header.

On the jsp page, you can directly reference the HelloTag tag. What I like is

The running result is as follows:

Someone asked me what to do if all tags like <td> have attributes. If there are any attributes, we simply add them without attributes. Let's implement an additional custom tag. I use the TagSupport class. From the figure above, we can see that this class implements the Tag interface, which makes Tag writing easier.

public class AddTag extends TagSupport{    private int num1;    private int num2;    public int getNum2() {        return num2;    }    public void setNum2(int num2) {        this.num2 = num2;    }    public int getNum1() {        return num1;    }    public void setNum1(int num1) {        this.num1 = num1;    }    public int doEndTag() throws JspException    {        JspWriter out=pageContext.getOut();        int num=num1+num2;        try {            out.print(num);        } catch (IOException e) {            e.printStackTrace();        }        return EVAL_PAGE;    }

Someone asked why you didn't write the doStartTag method. In fact, the TagSupport class has already been implemented for us. By default, it ignores the content in the tag. Now we are configuring the tld file here

<Tag> <name> add </name> <tag-class> com. lp. tags. addTag </tag-class> <attribute> // indicates the name of the attribute <name> num1 </name> <required> true </required> required <rtexprvalue> true </rtexprvalue> whether it is a runable expression </attribute> <name> num2 </name> <required> true </required> <rtexprvalue> true </rtexprvalue> </attribute> </tag>

Now we add the following code to jsp:

<% @ Taglib uri = "/WEB-INF/tlds/CustomTaglib. tld" prefix = "addtaglib" %>
<Body> custom tag: <% int num1 = Integer. parseInt (request. getParameter ("num1"); int num2 = Integer. parseInt (request. getParameter ("num2"); %> algorithm: <addtaglib: add num2 = "<% = num1 %>" num1 = "<% = num2 %>"> </addtaglib: add> </body>

Run the command again and check the result.

Some people have said that none of the tags you have written have the TAG content. Can you implement a tag with the content? OK, as we have just mentioned, SKIP_BODY indicates that the TAG content is ignored. Then, EVAL_BODY_INCLUDE indicates the content in the tag. Here we will implement a simple function of combining the three tags in Switch case default.

Let's first look at the SwitchTag tag.

Public class SwitchTag extends TagSupport {private static final long serialVersionUID = 1L; // used to determine whether the Sub-tag has been executed private boolean childTagExec; public SwitchTag () {childTagExec = false ;} public int doStartTag () throws JspException {// when the start label of the switch is encountered, the Child label does not execute childTagExec = false; return EVAL_BODY_INCLUDE; // execute the Case tag inside the Switch at this time}/*** is called by the sub-Tag Processor object to determine whether the Sub-TAG body can be executed * @ return */public synchronized boolean IsExec () {return (! ChildTagExec);}/*** if any sub-tag meets the condition, call this method to notify the parent tag * so that other sub-tags will ignore their own label bodies, to implement Switch case */public synchronized void childTagSucceeded () {childTagExec = true;} public void release () {childTagExec = false ;}

CaseTag

Public class CaseTag extends TagSupport {private static final long serialVersionUID = 1L; private boolean cond; // represents a condition (similar to case: 1) public CaseTag () {cond = false ;} public void setCond (boolean cond) {this. cond = cond;} public int doStartTag () throws JspException {Tag parent = getParent (); // obtain the parent Tag // determine whether to execute its own Tag if (! (SwitchTag) parent ). isExec () {return SKIP_BODY;} // if the condition is true, a sub-tag of the parent tag is notified to meet the condition. // otherwise, the label body is ignored if (cond) {(SwitchTag) parent ). childTagSucceeded (); return EVAL_BODY_INCLUDE;} else {return SKIP_BODY;} public void release () {cond = false ;}

DefaultTag

Public class DefaultTag extends TagSupport {private static final long serialVersionUID = 1L; public int doStartTag () throws JspException {Tag parent = getParent (); if (! (SwitchTag) parent ). isExec () {return SKIP_BODY;} (SwitchTag) parent ). childTagSucceeded (); // If none of the cases are met, run the Default label return EVAL_BODY_INCLUDE ;}}

We configure the tld file for the next time.

<tag>        <name>switch</name>        <tag-class>com.lp.tags.SwitchTag</tag-class>        <body-content>jsp</body-content>    </tag>    <tag>        <name>case</name>        <tag-class>com.lp.tags.CaseTag</tag-class>        <body-content>jsp</body-content>        <attribute>            <name>cond</name>            <required>true</required>            <rtexprvalue>true</rtexprvalue>        </attribute>    </tag>    <tag>        <name>default</name>        <tag-class>com.lp.tags.DefaultTag</tag-class>        <body-content>jsp</body-content>    </tag>

In <body-content> jsp </body-content>, jsp indicates that all functions of jsp are supported (compared to jsp9 built-in objects)

<Body> <% String userName = request. getParameter ("userName"); %> <mytag: switch> <mytag: case cond = '<% = userName. equals ("zhangsan") %> '> <% out. print ("Zhang San"); %> </mytag: case> <mytag: case cond = '<% = userName. equals ("lisi") %> '> <% out. print ("Li Si"); %> </mytag: case> <mytag: case cond = '<% = userName. equals ("wangwu") %> '> <% out. print ("Wang Wu"); %> </mytag: case> <mytag: default> <% out. print ("NONE"); %> </mytag: default> </mytag: switch> </body>

The execution result is as follows:

3.1: IterationTag Interface

All the TAG content we mentioned above is completed at one time. However, if the content of the loop title body is used, the IterationTag interface is used. This interface adds a method.

Public int doAfterBody () throws JspException this method indicates that each time the label body is processed, it is called, that is, it is called before the doEndTag method after the doStartTag method, if not, it will not be executed.

A new constant EVAL_BODY_AGAIN is added to execute the label body again. Now we can implement the function of retrieving multiple user information displays.

public class UserBean implements Serializable{    private static final long serialVersionUID = 1L;    public UserBean(){}    public UserBean(String userName,int age,String email)    {        this.age=age;        this.email=email;        this.userName=userName;    }    private String userName;    private int age;    private String email;    public String getUserName() {        return userName;    }    public void setUserName(String userName) {        this.userName = userName;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public String getEmail() {        return email;    }    public void setEmail(String email) {        this.email = email;    }}
Public class IterateTag extends TagSupport {private static final long serialVersionUID = 1L; private Iterator items; // gets the private String itemId of the Set; // identifies the private Object item of the Object; // public IterateTag () {items = null;} public void release () {items = null ;} /*** get the iteration object of the Set */public void setItems (Collection cl) {if (cl. size ()> 0) items = cl. iterator ();} public void setVar (String var) {this. itemId = var;} public int doStartTag () throws JspException {if (items. hasNext () // first executed {item = items. next () ;}else {return SKIP_BODY;} saveItems (); // Save the iteration object in pageContext return EVAL_BODY_INCLUDE;} public int doAfterBody () throws JspException {if (items. hasNext () // until every item in the iteration object is put into pageContext {item = items. next () ;}else {return SKIP_BODY;} saveItems (); return EVAL_BODY_AGAIN;} public void saveItems () {if (item = null) {pageContext. removeAttribute (itemId, pageContext. PAGE_SCOPE);} else {pageContext. setAttribute (itemId, item); // overwrite if the same id is added }}}
<tag>        <name>iterate</name>        <tag-class>com.lp.tags.IterateTag</tag-class>        <body-content>JSP</body-content>        <attribute>            <name>items</name>            <required>true</required>            <rtexprvalue>true</rtexprvalue>        </attribute>        <attribute>            <name>var</name>            <required>true</required>            <rtexprvalue>false</rtexprvalue>        </attribute>    </tag>
<Body> <% ArrayList al = new ArrayList (); UserBean user1 = new UserBean ("zhangsan", 25, "7808@outlook.com"); UserBean user2 = new UserBean ("lisi ", 15, "16455@qq.com"); UserBean user3 = new UserBean ("wangwu", 35, "7808@outlook.com"); al. add (user1); al. add (user2); al. add (user3 ); %> <table> <tr> <td> User Name </td> <td> age </td> <td> email </td> </tr> <iterator: iterate items = "<% = al %>" var = "user"> <jsp: useBean id = "user" class = "com. lp. beans. userBean "> </jsp: useBean> <tr> <td> <jsp: getProperty property = "userName" name = "user"/> </td> <td >$ {user. age }</td> <td >$ {user ["email"] }</td> </tr> </iterator: iterate> </table> </body>

The effect is as follows:

 

4: simple tag Development

To simplify the development of custom tags, the interface added by JSP2.0 to the development of simple tags is SimpleTag. Let's take a look at the main methods of SimpleTag.

4.1: public void setJspContext (JspContext pc) This method is called by the container and JspContext is set. JspContext is the base class of PageContext.

4.2: public void setParent (JspTag parent); set the parent tag

4.3: public JspTag getParent (); get parent tag

4.4: public void setJspBody (JspFragment jspBody, it can be executed multiple times.

4.5: public void doTag (), mainly processing the business logic of tags and tags

public class WelcomeSimpleTag extends SimpleTagSupport{  private JspFragment jspFragment;  private String name;  public void setJspBody(JspFragment jspBody)  {      this.jspFragment=jspBody;  }  public void setName(String name)  {      this.name=name;  }  public void doTag() throws JspException, IOException  {      JspContext jspContext=getJspContext();      JspWriter out=jspContext.getOut();      out.print(name);      jspFragment.invoke(null);  }

Then you can call it between jsp pages. You can develop simple labels on your own.

 

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.