JSP custom tag-tag attribute _ dynamic node Java school arrangement, jspjava

Source: Internet
Author: User

JSP custom tag-tag attribute _ dynamic node Java school arrangement, jspjava

Adding some attributes to custom tags makes tag functions more flexible and reusable. For example, if the previous blog used a simple tag to execute a certain number of times on the TAG body content, the tag cannot specify the number of times to be executed. It must be modified in the tag processor class, which is inconvenient, if you use tags with attributes, this problem can be well solved.

To make a simple tag have attributes, follow these two steps:

① Define attributes in the tag processor class and generate the setter method for each attribute;

② Add the attribute <attribute> label under the <tag> tag in the TLD file, and define its slave tag under the <attribute> tag, the <name> slave label is mandatory. <Attribute> the label has the following slave labels:

Name tag: used to specify the name of the attribute in the tag.

Required label: Specifies whether this attribute is required.

Rtexprvalue Tag: Specifies whether this attribute supports runtime expressions, such as JSP expressions (<% = value %>) and EL expressions ($ {value }). If it is set to "false", this attribute can only support strings.

Example 1: use simple tags to control the number of executions of the TAG body content (with attribute tags)
Compile the tag processor class:

Package com. bjpowernode. simpletag; public class LoopTagBody extends SimpleTagSupport {private int count; // defines an attribute to specify the number of cycles public void setCount (int count) {// set the setter method for this attribute this. count = count ;}@ Override public void doTag () throws JspException, IOException {JspFragment fragment = this. getJspBody (); for (int I = 0; I <this. count; I ++) {// you can specify the number of cycles by using the attribute. invoke (null );}}}

Define and describe the tag processor class in the TLD file, and specify the uri of the tag:

<?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>simpletag</uri>   <tag>     <name>loopbody</name>     <tag-class>com.bjpowernode.simpletag.LoopTagBody</tag-class>     <body-content>scriptless</body-content>     <attribute>       <name>count</name>       <required>true</required>       <rtexprvalue>true</rtexprvalue>     </attribute>   </tag> </taglib>

Import the taglib command at the beginning of the JSP page:

  <%@ taglib uri="simpletag" prefix="simple" %>

Finally, you can use the simple tag with attributes defined in the subject of the JSP page. You can use the "count" attribute to specify the number of TAG body loops:

<Simple: loopbody count = "5"> happy! <Br> </simple: loopbody>

Observe in the browser:

 

As shown in the preceding example, although the type of the "count" attribute in the LoopTagBody class of the tag processor is int, the type of the string is uploaded to the tag, this is because JSP containers support converting the attribute type (string) of tags to eight basic data types. If you define a non-eight basic data type attribute in the tag processor class, the preceding method must report an error because the JSP Container cannot convert the string to another type. Unless other types are used in tag properties:

Example 2:

 package com.bjpowernode.simpletag; public class DateAttributeTag extends SimpleTagSupport {   private Date date;    public void setDate(Date date) {     this.date = date;   }   @Override   public void doTag() throws JspException, IOException {     this.getJspContext().getOut().write(date.toString());   } }

Description in the TLD file (the beginning and end are omitted here. For details, see Example 1 ):

<tag> <name>showtime</name>    <tag-class>com.bjpowernode.simpletag.DateAttributeTag</tag-class>   <body-content>empty</body-content>   <attribute>       <name>date</name>       <required>true</required>       <rtexprvalue>true</rtexprvalue> </attribute> </tag>

Note: here the <rtexprvalue> label is required.

After the taglib command is imported on the JSP page (omitted here), use the simple tag just defined in the main body of the JSP page:

  <simple:showtime date="<%=new Date() %>"/>

Observe in the browser:

If the JSP page attribute is a string, because the tag processor class is not eight basic data types, you can only use JSP expressions or EL expressions to pass objects, therefore, the <rtexprvalue> label must be set to "true" in the TLD file ".

You have learned how to use simple tags, including those without attributes and those with attributes, and there is so much content that the rest can be developed based on what you have learned.

Example 3: Use simple tags for anti-leech protection

If a JSP page needs to prevent leeching by other websites, you can use a simple tag at the beginning of the JSP page, add some attributes, such as specifying the origin site to view the content of this page. specify where the request is redirected first if the URL is not specified.

Compile the tag processor class:

Package com. bjpowernode. simpletag; public class RefererTag extends SimpleTagSupport {private String site; // specify the URL of the private String location that allows access requests; // where to go to public void setSite (String site) {this. site = site;} public void setLocation (String location) {this. location = location ;}@ Override public void doTag () throws JspException, IOException {PageContext pageContext = (PageContext) t His. getJspContext (); HttpServletRequest request = (HttpServletRequest) pageContext. getRequest (); HttpServletResponse response = (HttpServletResponse) pageContext. getResponse (); String requestUrl = request. getHeader ("referer"); if (requestUrl = null |! RequestUrl. startsWith (site) {response. sendRedirect (request. getContextPath () + this. location); throw new SkipPageException ();}}}

Description in the TLD file (the beginning and end are omitted here. For details, see Example 1 ):

 <tag>     <name>referer</name>     <tag-class>com.bjpowernode.simpletag.RefererTag</tag-class>     <body-content>empty</body-content>     <attribute>       <name>site</name>       <required>true</required>       <rtexprvalue>true</rtexprvalue>     </attribute>     <attribute>       <name>location</name>       <required>true</required>       <rtexprvalue>true</rtexprvalue>     </attribute> </tag>

After the taglib command is imported on the JSP page (omitted here), use the simple tag just defined in the main body of the JSP page:

 <simple:referer site="http://www.bjpowernode.com" location="/index.jsp" /> <!DOCTYPE HTML> 

Result: To access the JSP page, you can only access the URL specified by the page attribute with the prefix of the requested URL, if it is a hyperlink in other web pages or directly enter the jsp url in the browser, the webpage specified by the location attribute will be redirected.

Example 4: Use a simple tag to filter and escape the HTML in the TAG body

Compile the tag processor class:

 package com.bjpowernode.simpletag; public class HtmlFilterTag extends SimpleTagSupport {   @Override   public void doTag() throws JspException, IOException {     JspFragment fragment = this.getJspBody();     StringWriter writer = new StringWriter();     fragment.invoke(writer);     StringBuffer buffer = writer.getBuffer();     String content = filter(buffer.toString());     this.getJspContext().getOut().write(content);   }   public String filter(String message) {     if (message == null)       return (null);     char content[] = new char[message.length()];     message.getChars(0, message.length(), content, 0);     StringBuilder result = new StringBuilder(content.length + 50);     for (int i = 0; i < content.length; i++) {       switch (content[i]) {       case '<':         result.append("<");         break;       case '>':         result.append(">");         break;       case '&':         result.append("&");         break;       case '"':         result.append(""");         break;       default:         result.append(content[i]);       }     }     return (result.toString());   } }

The filter method can refer to the Code in Tomcat (location: [Tomcat] ---> [webapps] ---> [examples] ---> [WEB-INF] ---> [classes] ---> [utils] ---> "HTMLFilter. java ").
Define and describe tags in a TLD file:

 <tag>     <name>filterhtml</name>     <tag-class>com.bjpowernode.simpletag.HtmlFilterTag</tag-class>     <body-content>scriptless</body-content>  </tag>

Use the custom simple tag in the main part of the JSP page:

<Simple: filterhtml> <a href = "www.baidu.com" rel = "external nofollow"> Baidu </a> </simple: filterhtml>

Observe in the browser:

Related Article

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.