Examples of jsp custom tag usage and jsp custom instances

Source: Internet
Author: User

Examples of jsp custom tag usage and jsp custom instances

This example describes the use of jsp custom labels. Share it with you for your reference. The details are as follows:

There is a mechanism in JSP that allows you to insert a tag similar to HTML in the JSP page. This article introduces the basic concepts and components of JSP custom tag, and how to develop and apply JSP custom tag.

What is tag

Using the HTML language, We can edit our webpage as follows:

<HTML>  <HEAD><TITLE>HELLO WORLD</TITLE></HEAD><BODY>HELLO WORLD</BODY></HTML>

Here we call </HEAD>, <TITLE>, and <BODY> a tag. HTML Markup is the control language for HTML documents. It is used to specify how the browser displays and prints documents. it is a phrase and symbol enclosed by a minor sign "<" and a minor sign ">, such as <Html> and </Body>. Many HTMl tags appear in pairs, such as <TITLE> </TITLE> and <Body> </Body>. In JSP, we can also customize our own tags for JSP pages, as shown in the following example:

<!—login.jsp--><%@ taglib uri="/tlds/taglib.tld" prefix="tagclass" %>

In the preceding example, </tagclass: login> is a JSP custom tag. Widtht and height are the attributes of the tag. <% @ Taglib uri = "/tlds/taglib. tld" prefix = "tagclass" %> is a tag library definition instruction, which will be discussed later. Custom tags in JSP are essentially a Java class with independent functions encapsulated in the form of tags. The use of tags reduces the Java code that is directly embedded into JSP pages, facilitates page layout, facilitates code reuse, and improves development efficiency.

Process of parsing tags on JSP servers

After a tag is embedded into a JSP page, how does the JSP server parse the tag? The meanings of each object are as follows:

Client: indicates the Client.
JSP-Server: JSP Server.
JSP-Page: JSP Page.
TLD: Mark database description files, define various attributes of tags and tags, and process files.
TagClass tag Handler

When a user accesses a JSP page, the request is sent to the JSP server. The JSP server calls the corresponding page according to the request. If the page contains a custom tag, the JSP service will access the TLD according to the page instruction <% @ taglib> to obtain information about the processing program, then call the constructor method of the processing program to start the marking processing program, and read the tag attributes and corresponding values. Call the corresponding set method for each object that does not have any attribute set. When a tag is used for the first time, no attribute is set. Therefore, the set method is called for each attribute. After the attribute is set, the JSP server calls the doStartTag () of the handler and then calls the doEndTag () method. Finally, the JSP server will continue to process the remaining pages and call the release () method at the end of the page to clear all the resources occupied.

TLD File

TLD (TLD: Tag Library Descriptor) file, a Tag definition file in standard XML format, used to store Tag information. Below is a typical TLD file.

<? Xml version = "1.0" encoding = "ISO-8859-1"?> <! -XML version and Character Set --> <! DOCTYPE taglibPUBLIC "-// Sun Microsystems, Inc. // dtd jsp Tag Library 1.1 // EN "" http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd "> <! -Document Type Definition --> <taglib> <! -This tag describes a tag library --> <tlibversion> 1.0 </tlibversion> <! -Mark the database version --> <jspversion> 1.1 </jspversion> <! -The JSP version used --> <shortname> tagclass </shortname> <! -Default name --> <tag> <name> login </name> <! -Tag name --> <tagclass> tagclass. login. login <! -Name of the corresponding class for processing the Tag --> </tagclass> <info> <! -Description of this identifier --> </info> <attribute> <! -Start to define the tag attributes --> <name> height </name> <! -Attribute name --> <required> true </required> <! -Indicates whether this attribute is required --> <rtexprvalue> true </rtexprvalue> <! -Indicates whether the property can be output using the JSP program segment --> </attribute> <name> width </name> <required> true </required> <rtexprvalue> true </rtexprvalue> </attribute> </tag> </taglib>

The TLD file defines a tag library with only one tag. the login tag calls an Applet to verify the validity of the user. The class for processing this tag is tagclass. login. login. Width and height are two attributes of the tag. Attribute is the value sent as a parameter when a tag is used. We can add several tags in the preceding example or add several attributes for each tag. When developing a tag library, we do not have to start from scratch and write a brand new TLD. We can use an integrated development environment or modify the above example.

TagLib command

How does the JSP server define a tag library when parsing a tag? This is the main responsibility of the TagLib command.

Taglib command

Define a tag library and its custom tag prefix.

JSP syntax

Copy codeThe Code is as follows: <% @ taglib uri = "URIToTagLibrary" prefix = "tagPrefix" %>
Example

<%@ taglib uri="/tlds/taglib.tld" prefix="tagclass" %>

Description

<% @ Taglib %> the command declares that the JSP file uses a custom tag and references the tag library,
The prefix of their tags is also specified. You must use the <% @ taglib %> command before using the custom tag.

Attribute

Uri = "URIToTagLibrary": Uniform Resource Identifier (URI) uniquely names the custom tag Based on the tag prefix. URI can be a relative or absolute path.
Prefix = "tagPrefix": prefix before the custom tag. In the preceding example, </tagclass: login>

Tag handle)

Let's take an example to see how to implement a Tag handle. First, let's take a look at its class diagram:
Let's take a look at its code:

package tagclass.login;import javax.servlet.jsp.tagext.TagSupport;import javax.servlet.jsp.*;import java.io.*;public class login extends TagSupport{public login(){super();}public int doStartTag() throws JspTagException{JspWriter out = pageContext.getOut();try{out.println("<APPLET CODEBASE=applet/login/ CODE=login.class width=200 height=100 > </APPLET>");}catch(Exception e){}return SKIP_BODY;}publicc int doEndTag()throws JsptagException{return EVAL_PAGE;}public void release(){super.release();}public void setWidth(String language){this.width = width;}public String getWidth(){return this.width;}public void setHeight(String height){this.height=height;}public String getHeight(){return this.height;}private String width;private String height;}

From the above we can see that there are several requirements for implementing a simple tag handler: ① Add a class to inherit the java. Servlet. jsp. tagext. TagSupport class. This class provides all the methods required by the java. Servlet. jsp. tagext. Tag interface. In addition, some basic APIs are required to enable the JSP Container to call our own tag handler. ② A get <attribute> and set <attribute> method must be created for each tag attribute. JSP containers need to use these methods to pass parameters. ③ Create a constructor and self-destructor for the token handler. JSP needs to use the constructor to start the processing program. The self-destructor is defined in the realwritable () method. At the end of the life cycle of the processing program, you need to call the self-destructor to release the resources occupied. ④ Create two methods named doStartTag () and doEndTag () to perform specific processing and output actions. These two methods are called when processing the start position and end position of the custom token. Their return values are static int defined in Tag Interface. These static values are:

SKIP_BODY implicit 0: Skip the code between the start and end labels.
EVAL_BODY_INCLUDE implicit 1: output the body content to an existing output stream.
SKIP_PAGE implicit 5: Ignore the remaining page.
EVAL_PAGE implicit 6: continue to execute the following page

Of course, the identifier also has its own shortcomings. The encapsulation process is inconvenient and has limited functions. For some logic descriptions that are not complex and have a single function, it is much easier to use JSP tags when the parameter requirements to be passed are not high. For most commercial logic applications, bean is much better than servlet control.

Appendix: complete code of the examples used in this article

JSP code: login. jsp

<%@ taglib uri="/tlds/taglib.tld" prefix="tagclass" %>

Tag description Library: taglib. tld

<?xml version="1.0" encoding="ISO-8859-1" ?><!DOCTYPE taglibPUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" " http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"><taglib><tlibversion>1.0</tlibversion><jspversion>1.1</jspversion> <shortname>tagclass</shortname><tag>  <name>login</name><tagclass>tagclass.login.login</tagclass>  <info>  </info><attribute>  <name>height</name>  <required>true</required>  <rtexprvalue>true</rtexprvalue>  </attribute><attribute>  <name>width</name>  <required>true</required>  <rtexprvalue>true</rtexprvalue>  </attribute></tag></taglib>

Token handler: login. java

package tagclass.login;import javax.servlet.jsp.tagext.TagSupport;import javax.servlet.jsp.*;import java.io.*;public class login extends TagSupport{public login(){super();}public int doStartTag() throws JspTagException{JspWriter out = pageContext.getOut();try{out.println("<APPLET CODEBASE=applet/login/ CODE=login.class width=200 height=100 > </APPLET>");}catch(Exception e){}return SKIP_BODY;}publicc int doEndTag()throws JsptagException{return EVAL_PAGE;}public void release(){super.release();}public void setWidth(String language){this.width = width;}public String getWidth(){return this.width;}public void setHeight(String height){this.height=height;}public String getHeight(){return this.height;}private String width;private String height;}

The Applet used in the tag handler: login. java

import java.awt.*;import java.awt.event.*;import java.applet.*;public class login extends Applet implements ActionListener{private String s_username;private String s_userpassword;private Button b_ok;private Button b_register;private Label l_username;private Label l_userpassword;private TextField t_username;private TextField t_userpassword;private GridLayout g_gridlayout;public void init(){b_ok=new Button("ok");b_register=new Button("register");l_username= new Label("name");l_userpassword=new Label("password");t_username=new TextField();t_userpassword=new TextField();b_ok.addActionListener(this);b_register.addActionListener(this);g_gridlayout=new GridLayout(3,2,10,10);this.setLayout(g_gridlayout);//this.setBackground(Color.blue);add(l_username);add(t_username);add(l_userpassword);add(t_userpassword);add(b_ok);add(b_register);}public void actionPerformed(ActionEvent ev){String s_label=ev.getActionCommand();if (s_label.equals("ok")){t_username.setText("name");}if (s_label.equals("register")){t_userpassword.setText("password");}}public void paint(Graphics g){}}

I hope this article will help you with JSP program design.

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.