The use of Jstl and El Expressions in JSP

Source: Internet
Author: User
Tags cos i18n time and date

JSTL (JSP standard tag Library, JSP standards tag libraries)

Jstl Tag Library is divided into 5 categories: Jstl core tag library, Jstl function tag library, database tag library, i18n format tag library, XML tag library.

Jstl's core tag libraries include: expression manipulation, Process control, iterative operations, and URL operations. The following is a summary of the usage of JSTL common tags:

One, expression operation

1. <c:out>

Function: Used to display the contents of the data.
Syntax 1: No ontology content
<c:out value= "Value" [escapexml= "{true|false}"] [default= "DefaultValue"]/>
Syntax 2: Ontology content
<c:out value= "Value" [escapexml= "{true|false}"]>
Default value
</c:out>
Property Description:
Value: values that need to be displayed.
Default: Displays the value specified by default if value is null.
EscapeXML: Whether to convert special characters, which is true by default. The default is to convert <, >, ', ', and & to &lt;, &gt;, & #039, & #034和 &amp. If set to False, no conversion is made.

2, <c:set>
Action: Used to store the value of a variable in a JSP scope or in a JavaBean property.
Syntax 1: Store value in a range of VarName variables
 <c:set value= "value" var= "VarName" [scope=] {page|request| Session|application} "]/>
Syntax 2: Store the data of the ontology content in a VarName variable scoped to scope
 <c:set var=" VarName "  [scope= "{page|request|session|application}"];
  .... Ontology content
 </c:set>
Syntax 3: Store value in the property attribute of the target object
 <c:set value= "value" target= " Target "property=" PropertyName "/>
Syntax 4: Store the data of the ontology content in the property properties of the target object
 <c:set target=" Target " Property= "PropertyName";
  Ontology content
 </c:set>
Property Description:
 value: The value to be stored.
 var: The name of the variable you want to deposit. The JSP scope of the
 scope:var variable. The default is the page range.
 target: is a JavaBean or map object.

If "target" is a map, "property" specifies a key to the map, and if "target" is a bean, "property" specifies a member field of the Bean.
If the "target" expression is null, the container throws an exception.
If the "target" expression is not a map or bean, the container throws an exception.
If the "target" expression is a bean, but the bean does not have a member field that matches the "property", the container throws an exception.
Property: The properties of the specified target object.

3. <c:remove>
Action: Removes the variable.
Syntax: <c:remove var= "VarName" [scope= "{page|request|session|application}"]/>
Property Description:
var: the variable to remove.
The JSP scope where the Scope:var variable is located, which defaults to the page range.

4. <c:catch>
Function: Used to handle the exception condition that generated the error and store the error information.
Syntax: <c:catch [var= "VarName"] >
... To crawl the wrong part
</c:catch>
Property Description:
var: stores the error information in the specified variable, which can be used to obtain an error message.

Second, Process Control


1. <c:if>
function: Like if judgment statement, used for expression judgment.
Syntax 1: No ontology content
<c:if test= "testcondition" var= "VarName" [scope= "{page|request|session|application}"]/>
Syntax 2: Ontology content
<c:if test= "Testcondition" [var= "VarName"] [scope= "{page|request|session|application}"]/>
... Ontology content
</c:if>
Property Description:
Test: When the expression in this property evaluates to True, the ontology content is executed, false is not executed, and the label must have a test property.
var: Stores the result of the test operation as true or false.
The JSP scope of the Scope:var variable.

2, <c:choose>, <c:when>, <c:otherwise>
Role: These three tags must be used in combination for process control.
Example:
<c:choose>
<c:when test= "${condition1}" >
Condition1 is True
</c:when>
<c:when test= "${condition2}" >
Condition2 is True
</c:when>
<c:otherwise>
Both Condition1 and Condition2 are false.
</c:otherwise>
</c:choose>
Example Description: When Condition1 is true, "Condition1 is true" is displayed, "Condition2 is true" when Condition1 is false and Condition2 is true. If both are false, both Condition1 and Condition2 are displayed as false.
Note: If both Condition1 and Condition2 are true, only "Condition1 is true" appears.
Limitation Description:
A, <c:when> and <c:otherwise> tags must be used between <c:choose> and </c:choose>.
b, in the same <c:choose>,<c:otherwise> must be the last label, and only one <c:otherwise> tag. <c:when> can have more than one.
C, in the same <c:choose>, when all <c:when> test is false, the <c:otherwise> ontology content is executed.

Three, iterative operation

1. <c:forEach>
Function: For loop control, it can sequentially browse the members of the collection (Collection). The mode of operation is that when the conditions are met, the <c:forEach> 's ontology content is continuously repeated.
Syntax 1: Iterating through all the members of a collection object
<c:foreach items= "Collection" [var= "VarName"] [varstatus= "Varstatusname"] [begin= "Begin"] [end= "End"] [step= "Step "]/>
... Ontology content
</c:forEach>
Syntax 2: Iteration specified number of times
<c:foreach [var= "VarName"] [varstatus= "Varstatusname"] begin= "Begin" end= "End" [step= "Step"]>
... Ontology content
</c:forEach>
Property Description:
Items: The collection object that is iterated.
var: holds the members of the collection object that are currently referred to.
Varstatus: Stores information about the member that is currently referred to. (Index: The indexes of the members currently referred to; count: The total number of members currently referred to, first: whether the member currently referred to is the initial member; Last: whether the member currently referred to is the final member).
Begin: The position at which the iteration begins and defaults to 0.
End: The position at the end of the iteration, which is the default.
Step: The number of intervals for each iteration, which defaults to 1.
Example:
<%
int atts[] = {1,2,3,4,5,6,7,8,9,10};
Request.setattribute ("Atts", Atts);
%>
<c:foreach items= "${atts}" var= "item" begin= "0" end= "9" step= "1" >
${item}</br>
</c:forEach>
This tag can also be used for normal loop control, as with a for loop. Such as:
<c:foreach begin= "1" end= "var=" Item ">
${item}</br>
</c:forEach>

2. <c:forTokens>
Function: Separates a string with the specified delimiter and iterates over the delimited array.
Syntax: <c:fortokens items= "Stringoftokens" delims= "delimiters" [var= "VarName"] [varstatus= "Varstatusname"] [begin= " Begin "] [end=" End "] [step=" Step "] >
Ontology content
</c:forTokens>
Property Description:
Items: A string that is delimited and iterated.
Delims: The character used to separate strings.
VAR: holds the member currently referred to.
Varstatus: Stores information about the member that is currently referred to. (Index: The indexes of the members currently referred to; count: The total number of members currently referred to, first: whether the member currently referred to is the initial member; Last: whether the member currently referred to is the final member).
Begin: The position at which the iteration begins and defaults to 0.
End: The position at the end of the iteration, which is the default.
Step: The number of intervals for each iteration, which defaults to 1.
Example 1:
<c:fortokens items= "A,b,c,d,e" delims= "," var= "Item" >
${item}
</c:forTokens>
Use the "," number to separate the string and iterate over the output delimited array of strings, and the output is "ABCDE".
Example 2:
<c:fortokens items= "A, B; C-d,e "delims=",;-"var=" Item ">
${item}
</c:forTokens>
Three delimiters ",", ";" and "-" are specified in Delims, so we can set all the characters we want to use as separate strings at a time. The output is still "ABCDE".

Iv. URL Actions


1. <c:import>
Role: include other static or dynamic files in the JSP Web page itself. Not only can you include files under the same Web application, but you can also include files from other Web application or other websites.
Grammar:
<c:import url= "url" [var= "VarName"] [scope= "{page|request|session|application}"] >
[<c:param name= "paramname" value= "Paramvalue"/>]
</c:import>
Property Description:
URL: The URL of another file to include to the JSP Web page itself. Must-Choose
var: stores other files that are included in a string into the specified variable. Options available
The scope of the Scope:var variable. Options available
<c:param>: Optional sub-label that is used to pass parameters to other Web pages that are included in the file.
Example:
<c:import url= "http://java.sun.com" >
<c:param name= "test" value= "1234"/>
</c:import>
Note: When the var variable is not specified in the <c:import> tag, the contents of the other Web file contained in it will be displayed directly, and if the var variable is specified, the content will be stored in the var variable, not displayed.

2. <c:url>
Function: Generates a URL.
Grammar:
<c:url value= "url" [context= "expression"] [var= "name"] [scope= "Scope"]>
[<c:param name= "expression" value= "expression"/>]
</c:url>
Example 1:
<a href= "<c:url value=index.jsp '/>" >index page</a>
In the <a> Hyperlink tab, generate a URL that points to index.jsp.
Example 2:
<c:url value= "index.jsp" >
<c:param name= "keyword" value= "${searchterm}"/>
<c:param name= "Month" value= "02/2003"/>
</c:url>
Generates a URL and passes the parameter, resulting in a result of index.jsp?keyword=*&month=02/2003,* representing the value of the searchterm passed.


3. <c:redirect>
Role: The client's request can be directed from one JSP Web page to another file.
Grammar:
<c:redirect url= "url" >
[<param name= "paramname" value= "paramvalue";]
</c:redirect>
Directs the request to other files that the URL points to.

Five, i18n format tag Library

Before you can format a label using I18N, insert the following directive first:

<%@ taglib prefix= "FMT" uri= "Http://java.sun.com/jsp/jstl/fmt"%>

1. <fmt:formatNumber>

Function: Format numbers as numbers, currencies, percentages

Grammar:

<fmt:formatnumber value= "Value" [var= "VarName"] [type= "{number|curreny|percent}"] [maxfractiondigits= "3"] [ Groupingused= "{True|false}"]/>

Property Description:
Value: values that need to be formatted

VAR: Another variable declaration of value

Maxfractiondigits: Number of decimal points reserved

2. <fmt:parseNumber>

Function: Formats numbers, currencies, and percentages of strings as numbers

Grammar:

<fmt:parsenumber value= "¥6789.36" [var= "Result"] [type= "{number|curreny|percent}"] >

Property Description:
Value: values that need to be formatted

VAR: Another variable declaration of value

3. <fmt:formatDate>

Function: Format time and date

4. <fmt:parseDate>
Function: Converts the time and date in the form of a string into a date-time type.

5. <fmt:setTimeZone>

Role: Set the default time zone in the JSP Web page.

6. <fmt:timeZone>

Role: Set the time zone for the code snippet in the tag body in the JSP Web page.

7. <fmt:setLocale>

Role: Set the locale in the JSP Web page.

8. <fmt:requestEncoding>

Function: The encoding used to set the request in the JSP Web page is equivalent to the requests in the JSP. Setcharacterencoding (String encoding).

9. <fmt:setBundle>

Role: Sets the default message resource.

10. <fmt:message>

function: Extracts the corresponding message content by keyword in the specified message resource.

11. <fmt:param>

Function: Sets the dynamic parameters for the message content when the message content is removed from the message resource.

12. <fmt:bundle>

Role: Set a message resource for the code snippet in the tag body.

Ii. Common Mistakes

JSP exception occurs when the application deployment is running, when using the JSTL library: According to TLD or attribute directive in tag file, attribute value does no accept any expressions, perhaps because of the use of the JSP2.0 version, while not using the backup version of the JSTL Core library (RT library), there are two ways to handle this:

1. If you do not want to use web-app_2_4.xsd and jstl1.1 then you can modify it in the following two ways

1). Modify Web. Xml.

<web-app 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-app_2_4.xsd" version= "2.4" >
Change to version 2.3

<! DOCTYPE Web-app Public "-//sun Microsystems, INC.//DTD Web Application 2.3//en" "Http://java.sun.com/dtd/web-app_2_3. DTD ">
<web-app>


2). Using the JSTL Core RT Library

There are two taglib pseudo-directives for the JSTL Core library, where the RT library is dependent on the property value of the JSP's traditional request, rather than relying on El to implement it (called the El Library. JSP2.0 will support EL)

JSP in the use of <%@ taglib uri=http://java.sun.com/jstl/core prefix= "C"%> in the 2.3 version can be, in 2.4 is not, this is the version incompatibility caused by, The version of the servlet is described later.

As long as the

<%@ taglib uri= "Http://java.sun.com/jstl/core" prefix= "C"%>
Switch
<%@ taglib uri=http://java.sun.com/jstl/core_rt prefix= "C"%>

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" utf-8 "%> <%@ pageImport= "com.cos.user,java.util.*"%> <%@ taglib uri= "Http://java.sun.com/jstl/core_rt" prefix= "C"%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" > Map<User,String[]> map =NewHashmap<user,string[]>(); String temp[]=NewString[2]; User User1=NewUser (); User1.setname ("Zhangsan"); User1.setage (20); temp[0] = "1"; temp[1] = "111111";                    Map.put (user1, temp); User User2=NewUser (); User2.setname ("Lisi"); User2.setage (22); Temp=NewString[2]; temp[0] = "2"; temp[1] = "2222222";          Map.put (User2, temp); Request.setattribute ("M", map); %> <c:foreach items= "${m}" var= "user" > <tr> <td>${user.key.name}</td&gt              ; <td>${user.key.age}</td> <td>${user.value[0]}</td> <td>${user.valu e[1]}</td> </tr> <br> </c:forEach> </body> 
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" utf-8 "%> <%@ pageImport= "com.cos.user,java.util.*"%> <%@ taglib uri= "Http://java.sun.com/jstl/core_rt" prefix= "C"%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" > Request.setattribute ("M",NULL); Request.setattribute ("MM", "BBB"); %> <c:out value= "${m}"default= "nnnnnn"/><br> <c:out value= "${mm}"default= "Nnnnnnlllllll"/><br> <c:set value= "Hello Word." var= "Cset" scope= "page"/>${cset}<br> <c:ifTest= "true" var= "T" > istrue&LT;/C:if> </body> 
<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" utf-8 "%> <%@ pageImport= "com.cos.user,java.util.*"%> <%@ taglib prefix= "C" uri= "Http://java.sun.com/jstl/core_rt"%> <%@ taglib P refix= "FMT" uri= "http://java.sun.com/jsp/jstl/fmt"%> <!             DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" > RMB 6789.3581 The result of formatting is (keep 3 decimal places):<c:out value= "${result}"/><br><br> <fmt:formatnumber value= "3.1415926" var= " Result "maxfractiondigits=" 2 "groupingused=" false "/> 3. 1415926 reserved two decimal places the result of formatting is:<c:out value= "${result}"/><br><br> <fmt:formatnumber value= "0.653789" type= " Percent "var=" result "maxfractiondigits=" 2 "groupingused=" false "/> 0. 653789 The result is in percent-based format:<c:out value= "${result}"/><br><br> </body> 
 <%@ page language= "java" contenttype= "text/html; charset=utf-8" pageencoding= "utf-8"%> <%@ page import  = "com.cos.user,java.util.*"%> <%@ taglib prefix= "C" uri= "Http://java.sun.com/jstl/core_rt"% > <%@ taglib prefix= "FMT" uri= "http://java.sun.com/jsp/jstl/fmt"%> <!             DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" > 


2: If you want to use jstl1.1 (recommended) Then follow the changes, very simple.


Jstl There are 1.0 and 1.1 difference issues, with El Recommendations need to be in the 1.1 version,


Using jstl1.1 only needs to be

The 1.0 is

<%@ taglib uri= "Http://java.sun.com/jstl/core" prefix= "C"%>

Into:

<%@ taglib uri= "Http://java.sun.com/jsp/jstl/core" prefix= "C"%>

The use of Jstl and El Expressions in JSP

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.