Custom tag learning for Servlet and JSP, servletjsp tag

Source: Internet
Author: User
Tags tld

Custom tag learning for Servlet and JSP, servletjsp tag

This article will describe the simple tag processor, which is not described here because the classic custom tag processor does not have a simple tag processor for ease of use.

Refer to: MOOC's JSP custom tag video;

Chapter 6 of Servlet, JSP, and Spring MVC beginner's guide;

Use SimpleTagSupport provided by JSP 2 to develop custom tags from IBM;

The JSP custom tag document of the cainiao tutorial.

Custom tag

  Custom tag

Custom labels encapsulate methods into custom tag processing classes and use methods and JSTL labels to separate the presentation of JavaBean from the business in JSP. Custom tags provide convenience that cannot be implemented in JavaBean, including allowing access to the objects hidden in JSP and their attributes.

The implementation of custom tags is called a tag processor, while a simple tag processor is a tag processor that implements the SimpleTag interface (or inherits the SimpleTagSupport class, A classic tag processor is a tag processor that implements the BodyTag interface (or inherits the BodyTagSupport class.

 

  Inheritance structure of custom tags

    JSP<---- Tag <---- IterationTag <---- TagSupport <---- BodyTagSupport <----- BodyTag

    JSP<---- SimpleTag <----- SimpleSupportTag

 

Simple Tag Processor

The simple tag processor has a simple life cycle. In the SimpleTag interface, there is only one method for tag triggering ------ doTag, and this method will only be executed once. Business logic, traversal, and page content operations are all implemented here. The page content in the simple tag processor is reflected in instances of the JspFragment class.

 

Lifecycle of simple tagsAs follows:

 

1) the JSP Container creates its instance through the non-parameter constructor of the simple tag processor. Therefore, the simple tag processor must have no parameter Constructor (generally, you do not need to write it yourself, by default ).

2) the JSP Container uses the setJspContext method to pass in the JspContext object. The most important method of this object is getOut (). It can return JspWriter and return the response to the front-end through JspWriter.

3) if the custom tag is nested by another custom tag, the JSP Container will call the setParent method.

4) the JSP Container calls the Set Method for each attribute defined in the label.

5) to process the page content, the JSP Container will also call the setJspBody method of the SimpleTag interface to pass the page content encapsulated by JspFragment. Of course, if there is no page content, the JSP Container will not call this method.

 

NextSimpleTagInterface Details:

 

Method

Description

DoTag () method

Is the core method used to write the tag processing logic.

SetParent (JspTag) Method

Pass the parent Tag Processor object to the tag processor.

GetParent () method

Obtains the parent tag object of the current tag.

SetJspContext (JspContext) Method

Pass the pageContext object of the JSP page to the tag processor object.

SetJspBody (JspFragment) Method

The JspFragment object representing the current TAG body is passed to the tag processor object. (The invoke (Writer) method in JspFragment is used to execute the code segment represented by the JspFragment object)

  

Is it a bit embarrassing to look at a large string of text above? The following is an example of implementing the SimpleTagSupport class (similar to implementing the SimpleTag interface.

First, you need to prepare a SimpleTag. tld file for registering custom tags. This file is in the apache-tomcat file, and the general address is inE: \ apache-tomcat-6.0.39 \ webapps \ examples \ WEB-INF \ jspThe name isJsp2-example-taglib.tld.

Use a jsp page that shows the current time as the first example:

 

  Create a custom tag:

1) create a tag processing class

package com.ny.tag2;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import javax.servlet.jsp.JspException;import javax.servlet.jsp.JspWriter;import javax.servlet.jsp.tagext.SimpleTagSupport;public class DisplayInfo extends SimpleTagSupport{    @Override    public void doTag() throws JspException, IOException {        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd  HH:mm:ss");        String dateStr = simpleDateFormat.format(new Date());        JspWriter jspWriter = getJspContext().getOut();        jspWriter.write(dateStr);    }}

 

2) create a tag Library File

Create. tld files (such as nyTag. tld), and then open the jsp2-example-taglib.tld file, which has the taglib configuration we need, open this file and find the following code segment, copy to nyTag. in tld.

If the tid file is located under the WEB-INF file, Tomcat automatically loads the tag library in the tld file. If it is in another location, you can also configure it in web. xml.

<?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>/SimpleTagLibrary</uri></taglib>

 

3) Register tags in the tag Library File

<?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>ny</short-name>    <uri>/ny-tag</uri>    <tag>        <name>dateInfo</name>        <tag-class>com.ny.tag2.DisplayInfo</tag-class>        <body-content>empty</body-content>    </tag></taglib>

① <Short-name>: Specifies the recommended prefix (this attribute will appear when tags are introduced in the jsp page ).

② <Uri>: indicates the uri used to reference this tag Library (note thatYes uri, not url).

③ <Tag>: indicates the information of the tag to be defined.

Where,Attributes that can be set by tagAs follows:

 

Attribute

Description

Name

Defines the attribute name. The attribute name of each tag must be unique.

Tag-class

Specifies the ing Java class.

Required

Specify whether the attribute is required or optional. If required, set it to true.

Rtexprvalue

Declares whether the label attribute is valid when the expression is run. If the label attribute is valid, the value is true.

Type

Defines the Java class type of this attribute. The default value is String.

Decription

Description

Fragment

If this attribute is declared, the attribute value is considered as a JspFragment.

Bodycontent

Specify the limits of the label body. You can find the following values (for more information, see references): a) empty: specifies that the label can only be used as a null label; b) scriptless: the TAG body specified for this tag can be a static HTML element or expression language, but JSP scripts are not allowed.

 

4) introduce the tag Library to the page

 

<%@ taglib prefix="ny" uri="/ny-tag"%>

 

 

 

5) use tags on the page

 

<body>    <imooc:dateInfo/></body>

 

  

Therefore, the code on the JSP page is:

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ taglib prefix="imooc" uri="/imooc-tag2" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  

Is it quite simple? In fact, the usage of custom tags is more than that. Come on!

 

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.