Learn how to use JSP built-in tags, jstl tag libraries, and custom tags

Source: Internet
Author: User
Tags tag name tld

Categories of JSP Tags:

1) built-in label (action tag): No need to import tags on JSP page

2) Jstl Tags: need to import tags in JSP pages

3) Custom Tags: developer self-defined, need to import tags on JSP page

1. Built-in label (action tag):

<jsp:forward/> forwarding Label:

Syntax: <jsp:forward page= "/myjsp001.jsp" ></jsp:forward>
Equivalent to Java code: Request.getrequestdispatcher ("/MYJSP001.JSP?NAME=JXF"). Forward (request, response);
Note: However, the forwarding of Java code can be passed through the URL with parameters, and the forwarding label needs to be passed the following <jsp:param> tag to implement the parameter

<jsp:pararm/> Parameter tags:

Syntax:  <jsp:param value= "jxf" name= "name"/> <%--pass a parameter named name, with a value of JXF, the parameter is generally used as a sub-label for other labels using--%> combined with <jsp: Forward> label usage: <jsp:forward page= "/myjsp001.jsp" > <jsp:param value= "jxf" name= "name"/></jsp: Forward>

<jsp:include/> include tags:

Syntax: <jsp:include page= "/myjsp001.jsp" >        <jsp:param value= "jxf" name= "name"/><%-- Parameters can be passed to the included page--%></jsp:include>jsp also contains a directive, but also a page containing additional pages between them: 1, the first is the syntax of different <jsp:include page= "/ myjsp001.jsp "> <% @inclue file=" included pages "%> 2, <jsp:include> can pass parameters, <% @inclue%> not 3, <jsp: INCLUDE>: The containing page and the included page are compiled into two Java source files, referenced  <% @inclue%> at run time;: Include page merged with included page compiled into a Java source file
2. Jstl Label:

JSTL (Java standard tag Libarary-java standards Tag Library)

Jstl label type: Core tag library (c tag Library)//The main introduction of the C tag library, because with a lot of internationalization tags (fmt tag library) El function library (FN function library) XML tag library (x Tag Library)//generally do not use the library, this is data manipulation, and data operations should be in the DAO layer, JSP pages are mainly used to display data SQL tag library (SQL Tag Library)//similar to the XML tag library, should not manipulate the data in JSP pages (of course they can be written on the JSP page)
Use the JSTL tag library using the premise (here, for example, the C tag library):

1, Import JSTL Support package: Jstl-1.2.jar (If you choose Java EE5.0 when creating a project with MyEclipse, you do not need a guide package, the project already contains)

2. Import the tag library using the TAGLIB Directive in the page

The URI name in the <%--uri:tld file, prefix: Tag prefix--%>
<% @taglib uri= "Http://java.sun.com/jsp/jstl/core" prefix= "C"%>

How do URIs and prefix write? Take the tag library as an example:

Project name->java EE 5 libraries->jstl-1.2.jar->meta-inf-c.tld

The main tags of the C tag library:

<c:set> Tags : Used to save data to a domain object

<%--var is the property name value for the property value scope to save the property to that domain object, the default is the page field--%>    <%--is equivalent to the Java code <%pagecontext.setattribute (" Name "," JXF ")--%>    <c:set var=" name "value=" JXF "  scope=" page "></c:set>    ${name}<%-- The EL expression outputs the Name property value in the page field--%>

<c:out> Tags : displaying data

<%--value: Output to the browser value, ${name}el expression takes the value of the Field object property value to name,
Default: Defaults displayed when value is NULL,
EscapeXML: Indicates whether to escape to XML format (also understood as plain text format), true to escape, default false--%> <c:out value= "${name}" default= "

<c:if> Tags : but conditional judgment

<%--test support El expression--%>      <c:if test= "${true}" >          conditions set!      </c:if>

<c:choose>+<c:when>+<c:otherwise> tags : multi-conditional judgment

<%--equivalent to if else structure, when one condition satisfies the other conditions are not satisfied, certificate: this instance only outputs 10>5--%>      <c:choose>          <c:when test= "${10>5} ">              10>5<br/>          </c:when>          <c:when test=" ${6>2} ">              6>2<br/>          </c:when>          <c:otherwise>              conditions are not established          </c:otherwise>      </c:choose>

<c:forEach> Tags: traverse

      <%--begin      : from which element begins the traversal, the default starting from 0 end    : to which element ends. Default to last element      step     : Step, default 1      items    : Data to traverse (collection)       var    : The name of each element       Varstatus: The state object that is currently traversing the element. (Count property: Current position, starting from 1)
--%> <%
student{
public String name;
public int age;
Public Student (String Name,int age) {
THIS.name = name;
This.age = age;
}
    }//list Data Preparation list<student> List = new arraylist<student> (); List.add (New Student ("name001", 18)); List.add (New Student ("name002", 19)); List.add (New Student ("name003", 20)); Pagecontext.setattribute ("list", list);////map data preparation in the field map<string,student> Map = new Hashma P<string,student> (); Map.put ("001", New Student ("name001", 18)); Map.put ("002", New Student ("name002", 19)); Map.put ("003", New Student ("name003", 20)); Pagecontext.setattribute ("map", map);////array data preparation in the field student[] array = new student[]{n EW Student ("name001"), New Student ("name002", +), new Student ("name003", 20)}; Pagecontext.setattribute ("array", array);//%> <%--traversal list--%> <c:foreach var= "student" begin= "in the domain 0 "end=" 2 "items=" ${list} "step=" 1 "varstatus=" Varsta "> name:${student.name}---Age:${student.age}<br/> </c:forEach> <%--traverse map--%> <c:foreach var= "student" begin= "0" end= "2" items= " ${map} "step=" 1 "varstatus=" Varsta "> Key:${student.key}---name:${student.value.name}---age:${student.value.age }<br/> </c:forEach> <%--Traversal array--%> <c:foreach var= "student" begin= "0" end= "2" items= "${array}" step= "1" varstatus= "Varsta" > name:${student.name}---age:${student.age}<br/> </c:forEa Ch> <%--General traversal of the collection or array is all traversal, so write only 2 properties Var and items, the other takes the default value--%> <c:foreach var= "student" items= "${array}" > Name:${student.name}---age:${student.age}<br/> </c:forEach>

<c:forTokens> Tags: cutting strings

<%--      cut string, equivalent to the Split function      var: cut out every part of the string      items: The string to be cut      delims: The split character, if the content is a string, Then each character of the string is treated as a segmented character      such as: items= "A-b-c=d=e" dilims= "-=", the result of which is a,b,c,d,e--%>  <%      //Data Preparation      String str = "a-b-c=d=e";      Pagecontext.setattribute ("str", str); %>      <c:fortokens var= "item" items= "${str}" delims= "-=" > ${item}<br/> </c      : Fortokens>
3. Custom Tags:

When the JSTL tag Library has not been able to meet our needs, we need to develop custom tags to meet our needs, the custom tag is actually a common Java class, inheriting the Simpletagsupport class.

Before you introduce a custom label, you'll introduce the Simpletagsupport class:

The Simpletagsupport class inherits from the Simpletag interface, while the Simpletag interface has the following 4 methods, which can also be understood as the life cycle of the label processor class:

1 public Interface Simpletag extends Jsptag {2  3/** 4      * The method that is called when the label is executed, must be called 5      */6 public     void Dotag ( ) throws Javax.servlet.jsp.JspException, java.io.IOException; 7      8     /** 9      * Sets the parent tag object, passing in the parent tag object, which calls the      */11 public     void SetParent (jsptag parent) when the label has a parent tag;    13     /**14      * Set Jspcontext object, in fact, his real incoming is its subclass PageContext15      */16 public     void Setjspcontext (Jspcontext pc );     /**19      * Set the label body content. The tag body content is encapsulated into the Jspfragment object and then passed in Jspfragment object      */21 public     void Setjspbody (Jspfragment jspbody); 22 23}

Simpletagsupport class on the basis of the encapsulation of 3 methods, easy to customize the label class writing, the implementation of this method is relatively simple, is to maintain a variable internally, through the set method to assign it, and then return to the object, This inherits the Simpletagsupport to get as PageContext object directly calls Getjspcontext () can.

1 part of the/*simpletagsupport class */2 public class Simpletagsupport implements Simpletag 3 {4/** Reference to the     enclosing Tag. */5     private Jsptag Parenttag; 6      7/** The JSP context for the     upcoming tag invocation. */8     Private Jspco ntext Jspcontext; 9     /** The body of the     tag. */11     Private jspfragment jspbody;12 public     void SetParent (jsptag parent {         This.parenttag = parent;15     }16, public     Jsptag getParent () {         return this.parenttag;     }20 public     void Setjspcontext (Jspcontext pc) {         This.jspcontext = pc;23    }24 25< c20/>protected Jspcontext Getjspcontext () {         return this.jspcontext;27     }28 public     void Setjspbody (jspfragment jspbody) {         this.jspbody = jspbody;31     }32 protected    jspfragment     Getjspbody () {         return this.jspbody;35     }36}
To write a custom label:

To write a custom label for example: function: Output A word to the browser "Welcome to the blog garden"

1) Write a generic Java class (Outinfo.java), inherit the Simpletagsupport class, and override the Dotag method. (The JSP file is finally compiled into a Java file, and viewing the Java file shows that the _jspservice method creates a Label class Outinfo object and executes the Dotag method.) After compiling the original file path: such as D:\Program Files\tomcat\apache-tomcat-6.0.39\work\catalina\localhost\tag\org\apache\jsp\xxx.java)

1/* 2  * Outinfo.java 3 */  4 public class Outinfo extends Simpletagsupport {5      6     @Override 7 public     VO ID Dotag () throws Jspexception, IOException {8         PageContext PageContext = (PageContext) getjspcontext (); 9         Pagecontext.getout (). Write ("The bouquet is welcome to the blog Park");     }11}

2) the TLD file (JXF.TLD) is established in the Web-inf directory of the Web project, which is the declaration file for the tag library and is configured with the appropriate information. (You can refer to the TLD file of the core tag library, such as: Project/java EE 5 libraries/jstl-1.2jar/meta-inf/c.tld)

 1 <?xml version= "1.0" encoding= "UTF-8"?> 2 3 <taglib xmlns= "Http://java.sun.com/xml/ns/javaee" 4 xmlns:xsi = "Http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee/http Java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd "6 version=" 2.1 "> 7 8 &LT;DESCRIPTION&GT;JSTL 1.1 core Library</description> 9 <display-name>jstl core</display-name>10 <tlib-version>1.1</ tlib-version>11 <!--tag Library prefix taglib directive prefix properties-->12 <short-name>jxf</short-name>13 <!--TLD file                     The unique token of the taglib directive in the URI attribute-->14 <uri>http://jxf.tag</uri>15 <tag>17 <description>18 This is a description of the custom label and can be prompted in MyEclipse </description>20 <!--tag name-->21 <name>outinf O</name>22 <!--the end name of the label class-->23 &LT;TAG-CLASS&GT;JXF. Outinfo</tag-class>24 <body-content>scriptless</body-content>25 <!--<attribute>26 <description>27 This is the description of the attribute &lt ;/description>29 <name>var</name>30 <required>false</required>31 <rt exprvalue>false</rtexprvalue>32 </attribute>-->33 </tag>34 </taglib>

3) Import the custom tag library in the header of the JSP page

<% @taglib uri= "Http://jxf.tag" prefix= "JXF"%>

4) Use a custom label in the JSP

<jxf:outInfo></jxf:outInfo>

5) JSP page

1 <%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%> 2 <% @taglib uri= "Http://jxf.tag" prefix = "JXF"%> 3 <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > 4 
Custom tags can do:

1) control the content output of the label body

1         /*2          * 1) output tag title content 3          */4         jspfragment jspbody = Getjspbody (); 5         //Method: Invoke (Java.io.Writer out) 6         //When the parameter is null is equivalent to Jspbody.invoke (Getjspcontext (). Getout ()); 7         jspbody.invoke (NULL);

2) control the remaining contents of the label output

1         /*2          * 2) control the remaining contents of the label body Output 3          * After throwing a skippageexception exception, the label body remaining content output 4          */5         throw new Skippageexception ();

3) Change the contents of the label body

1         /*2          * 3) Change the contents of the tag body and output to the browser 3          */4         //Get to the tag body content and save to the custom paragraph punch character Stream 5         stringwriter sw = new StringWriter (); 6         //jspbodystring Gets the contents of the tag Body 7         String jspbodystring =  sw.tostring (); 8         jspbodystring = "Simply change the value of the string"; 9         Getjspcontext (). Getout (). write (jspbodystring);//Output to Browser

4) Labels with attributes (example of <c:choose>+<c:when>+<c:otherwise> tags that mimic the C tag)

Write 3 Custom Label processor classes Choosetag.java, when.java, otherwise.jave

1/* 2  * Choosetag.java 3 */  4 public class Choosetag extends Simpletagsupport {5     private Boolean flag = Fals E 6  7 Public     Boolean Isflag () {8         return flag; 9     }10 one public     void Setflag (Boolean flag) {12
   
    this.flag = flag;13     }14     @Override15 public     void Dotag () throws Jspexception, IOException {         Getjspbody (). Invoke (null);     }18}
   
/* * Whentag.java */public class Whentag extends Simpletagsupport {    private boolean test;        The attribute in the TLD file must have a corresponding set method, otherwise the error public    void Settest (Boolean test) {        this.test = test;    }    @Override public    void Dotag () throws Jspexception, IOException {        Choosetag parent = (Choosetag) getParent ();        if (!parent.isflag ()) {            if (test) {                Parent.setflag (true);                Getjspbody (). Invoke (null);}}}    
1/* 2  * Otherwisetag.java 3 */  4 public class Otherwisetag extends Simpletagsupport {5     @Override 6     p ublic void Dotag () throws Jspexception, IOException {7         Choosetag parent = (Choosetag) getParent (); 8         if (!parent . Isflag ()) {9             getjspbody (). Invoke (null);         }11     }12}

TLD file

 1 <?xml version= "1.0" encoding= "UTF-8"?> 2 3 <taglib xmlns= "Http://java.sun.com/xml/ns/javaee" 4 xmlns:xsi = "Http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee/http Java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd "6 version=" 2.1 "> 7 8 &LT;DESCRIPTION&GT;JSTL 1.1 core Library</description> 9 <display-name>jstl core</display-name>10 <tlib-version>1.1</ tlib-version>11 <!--tag Library prefix taglib directive prefix properties-->12 <short-name>jxf</short-name>13 <!--TLD file The unique token of the taglib directive in the URI attribute-->14 <uri>http://jxf.tag</uri>15 <tag>17 <name>choosetag</ Name>18 &LT;TAG-CLASS&GT;JXF.     choosetag</tag-class>19 <body-content>scriptless</body-content>20 </tag>21 <tag>22 <description>23 Custom when label </description>25 <name>whentag</name>2     6<tag-class>jxf. whentag</tag-class>27 <body-content>scriptless</body-content>28 <attribute>29 < DESCRIPTION&GT;30 when Tag properties test31 </description>32 <!--tag Processor class must have a corresponding set method, otherwise it will be an error, such as The corresponding label processor class should have the Gettest () method. -->33 <name>test</name>34 <!--Whether this property is required, true is required, false is not required-->35 <requir ed>true</required>36 <!--Whether this property supports El expression true support, false does not support-->37 <rtexprvalue>true</rt     exprvalue>38 </attribute>39 </tag>40 <tag>41 <name>otherwisetag</name>42 <tag-class>jxf. otherwisetag</tag-class>43 <body-content>scriptless</body-content>44 </tag>45 </taglib >

JSP code

 1 <%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%> 2 <% @taglib uri= "Http://jxf.tag" prefix= "JXF"%> 3 <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > 4 

Learn how to use JSP built-in tags, jstl tag libraries, and custom tags

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.