JavaWeb study notes 11--JSTL tag library

1. Introduction to JSTL:

The full name of JSTL is JavaServer Pages Standard Tag Library, the Chinese name is JSP Standard Tag Function Library, and the latest version is 1.2. JSTL is a standard specification specified by JCP (Java Community Process), which mainly provides Java Web developers with a standard and general tag function library.

Web program developers can use JSTL and EL to develop Web programs, replacing the traditional practice of embedding Java programs (Scripting) directly on the page to improve program readability, maintainability and convenience.

Since it is a library file, we have to download it first. Download link: http://tomcat.apache.org/

Click on Taglibs in the red box in the figure above to enter the following interface:

Click the red box in the above picture to enter the following interface:

In the picture above, click the latest version to download.

After downloading, copy the jar package to the /WebContent/WEB-INF/lib directory of the JavaWeb project to use it .

 

The tag function library provided by JSTL is mainly divided into five categories:

  • (1) Core tag library
  • (2) I18N-capable formatting tag library
  • (3) SQL tag library (SQL tag library)
  • (4) XML tag library
  • (5) Functions tag library

The most commonly used is the first one, the others are not very commonly used.

The Core tag library mainly includes the following:

1. Expression label:

  • <c:out> : Mainly used to display the content of the data, just like <%= scripting-language %>
  • <c:set>: Mainly used to store variables in the JSP scope or JavaBean properties
  • <c:remove>: mainly used to remove variables
  • <c:catch>: mainly used to deal with abnormal conditions that generate errors, and store the error information (less used)

2. Process control:

  • <c:if> : The purpose is the same as the if we generally use in the program
  • <c :choose> : itself is only used as the parent tag of <c:when> and <c:otherwise>
  • <c :when>/<c :otherwise> : When using <c:when> and <c:otherwise> for flow control, both must be subtags of <c:choose> (similar to switch... case...)

3. Iterative operation:

  • <c :forEach> : Loop traversal, which can browse through the members of the collection in sequence. The way it works is that when the conditions are met, the body content of <c:forEach> will be repeatedly executed.
  • <c :forTokens>: Used to browse all members of a string, whose members are separated by delimiters.

These tags are described in detail below.

Second, the core tag library:

Contains common work in web applications, such as: looping, expression assignment, basic input and output , etc.

1. Expression label:

  • <c:out> : Mainly used to display the content of the data, just like <%= scripting-language %>
  • <c:set>: Mainly used to store variables in the JSP scope or JavaBean properties
  • <c:remove>: mainly used to remove variables
  • <c:catch>: mainly used to deal with abnormal conditions that generate errors, and store the error information (less used)

Code example:

  • <c:out> tag

Create a new JavaWeb project Test08, and the index.jsp code is as follows:

 
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
3     <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 5 <html>
 6 <head>
 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 8 <title>Insert title here</title>
 9 <%
10     request.setAttribute("name", "smyhvae");
11 %>
12 </head>
13 <body>
14     <c:out value="${requestScope.name} "></c:out>
15  
16 </body>
17 </html>
 

Lines 03, 10, 14 are the code I added.

Line 03 (fixed code): Use JSTL and don't forget to import the tag library. prefix="c" is the prefix, and "c" represents the expression "<c:out>". The namespace is filled in the uri, and you can select http://java.sun.com/jsp/jstl/core through the code prompt. This uri can be found in the following way: in the Java Reasources/Libraries/Web App Libraries/jstl.jar/META-INF directory many files in tld format, these tld files refer to the declaration file of the tag library:

The c.tld file in the above figure represents the core tag library. Open it and you can see the uri:

In fact, the 03rd line of code is fixed and dead, you can add it, you don't need to go into it.

Once the core tag library is introduced, in the body tag, as long as you enter "<c", you can see many tags through code prompts.

We add an attribute to the request on line 10, and then we can output this value through the out output tag on line 14 (of course, we can also use EL expressions to output), run the program, and the effect is as follows:

  • <c:set> tag
 
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3     <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 5 <html>
 6 <head>
 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 8 <title>Insert title here</title>
 9 <%
10     request.setAttribute("name", "smyhvae");
11 %>
12 </head>
13 <body>
14 <%--output tag--%>
15     <c:out value="${requestScope.name} "></c:out>
16     
17 <%--Define variable label--%>
18     <c:set var="age" value="22"></c:set>    
19     ${age }
20  
21 </body>
22 </html>
 

See lines 18 and 19.

The effect is as follows:

 

2. Process control:

  • <c:if> : The purpose is the same as the if we generally use in the program
  • <c :choose> : itself is only used as the parent tag of <c:when> and <c:otherwise>
  • <c :when>/<c :otherwise> : When using <c:when> and <c:otherwise> for flow control, both must be subtags of <c:choose> (similar to switch... case...)

Create a new index2.sp file. code show as below:

 
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 5 <html>
 6 <head>
 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 8 <title>Insert title here</title>
 9 <%
10     request.setAttribute("name", "smyhvae");
11 %>
12 </head>
13 <body>
14
15 <%--Process control label if --%>
16     <c:if test="${not empty requestScope.name }">
17 Welcome, ${requestScope.name }
18     </c:if>
19
20     <c:if test="${empty requestScope.name }">
21 Please login to operate
22     </c:if>
23     <br />
24
25 <%--Process control label choose --%>
26     <c:set var="age" value="22"></c:set>
27
28     <c:choose>
29         <c:when test="${age<18 }">
30 Minors are not allowed to enter.
31         </c:when>
32         <c:when test="${age>=18 && age<50 }">
33 Welcome.
34         </c:when>
35         <c:otherwise>
36 Seniors, please take care of your body.
37         </c:otherwise>
38     </c:choose>
39
40 </body>
41 </html>
 

Lines 15 to 22 are if tags (the function of the if statement is the same), and the content in test in line 16 must be a boolean value: we add the value of name in line 10, and then judge the name of the name in lines 16 and 20. Whether the value is empty, and then make a judgment.

Lines 25 to 38 are choose tags (the same function as switch...case...).

Run the program, the effect is as follows:

 

3. Iterative operation:

  • <c :forEach> : Loop traversal, which can browse through the members of the collection in sequence. The way it works is that when the conditions are met, the body content of <c:forEach> will be repeatedly executed.
  • <c :forTokens>: Used to browse all members of a string, whose members are separated by delimiters.

Code example:

  • <c :forEach>

Create a new class User as the traversed object. User.java code is as follows:

 
1 package com.vae.bean;
 2
 3 public class User {
 4     private String name;
 5     private String sex;
 6     private int age;
 7     public User() {
 8         super();
 9     }
10     public User(String name, String sex, int age) {
11         super();
12         this.name = name;
13         this.sex = sex;
14         this.age = age;
15     }
16     public String getName() {
17         return name;
18     }
19     public void setName(String name) {
20         this.name = name;
21     }
22     public String getSex() {
23         return sex;
24     }
25     public void setSex(String sex) {
26         this.sex = sex;
27     }
28     public int getAge() {
29         return age;
30     }
31     public void setAge(int age) {
32         this.age = age;
33     }
34     @Override
35     public String toString() {
36         return "User [name=" + name + ", sex=" + sex + ", age=" + age + "]";
37     }
38
39     
40 }
 

Create a new file index3.jsp with the following code:

 
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%@page import="com.vae.bean.User,java.util.*"%>
 4 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 5 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 6 <html>
 7 <head>
 8 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 9 <title>Insert title here</title>
10
11 <%
12     List<User> users = new ArrayList<User>();
13 User u1 = new User("Life One", "Male", 22);
14 User u2 = new User("Life No. 2", "Male", 23);
15     User u3 = new User("vae", "女", 24);
16     users.add(u1);
17     users.add(u2);
18     users.add(u3);
19     request.setAttribute("users", users);
20 %>
21 </head>
22
23 <body>
24     <table border="1">
25         <tr>
26             <th>name</th>
27             <th>sex</th>
28             <th>age</th>
29         </tr>
30
31         <c:forEach items="${requestScope.users }" var="user">
32             <tr>
33                 <td>${user.name}</td>
34                 <td>${user.sex}</td>
35                 <td>${user.age}</td>
36             </tr>
37         </c:forEach>
38 </body>
39 </html>
 

The core code is lines 31 to 37.

In lines 12 to 19, we add the values ​​of multiple user objects to the List and put them into the request. Then add a table on line 24, and traverse the contents of the User object through <c:forEach> in the table. Here, two attributes in <c:forEach> are used: "items" in line 31 indicates the collection that needs to be iterated. , "var" means a variable defined each time it is fetched.

Run the program, the effect is as follows:

Attributes in <c:forEach>:

We used two properties in <c:forEach> in line 31 of the code above: items and var. Next, let's learn about other properties:

  • begin: Indicates which index to start from, generally not written;
  • end: Indicates the end position. If you need to traverse ten lines, write 10 here.
  • step: Increment.

The above three properties are used less frequently.

  • varStatus: The current status. Its status is as follows:

            index index starts at 0

            count starts the current traversal count from 1

            current the object currently being iterated over

            whether first is the first

            whether last is the last        

Let's take varStatus as an example. We further add to the index3.jsp code above:

index3.jsp:

 
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%@page import="com.vae.bean.User,java.util.*"%>
 4 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 5 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 6 <html>
 7 <head>
 8 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 9 <title>Insert title here</title>
10
11 <%
12     List<User> users = new ArrayList<User>();
13 User u1 = new User("Life One", "Male", 22);
14 User u2 = new User("Life No. 2", "Male", 23);
15     User u3 = new User("vae", "女", 24);
16     users.add(u1);
17     users.add(u2);
18     users.add(u3);
19     request.setAttribute("users", users);
20 %>
21 </head>
22
23 <body>
24
25     <table border="1">
26         <tr>
27             <th>name</th>
28             <th>sex</th>
29             <th>age</th>
30 <th>Status Value</th>
31         </tr>
32
33         <c:forEach items="${requestScope.users }" var="user" varStatus="status">
34             <tr>
35                 <td>${user.name}</td>            
36                 <td>${user.sex}</td>            
37                 <td>${user.age}</td>            
38                 <td>
39                 index :${status.index }<br/>
40                 count :${status.count }<br/>
41                 current :${status.current }<br/>
42                 first :${status.first }<br/>
43                 last :${status.last }<br/>
44                 </td>           
45             </tr>
46         </c:forEach>
47     </table>
48 </body>
49 </html>
 

Line 30 in bold, the varStatus property in line 33, lines 38 to 44 is the code I added further. Run the program, the effect is as follows:

Through the above picture, let's review the various states of varStatus, it is clear at a glance:

  • index index starts at 0
  • count starts the current traversal count from 1
  • current the object currently being iterated over
  • whether first is the first
  • whether last is the last 

Code example:

  • <c :forTokens>

Create a new index4.jsp file with the following code:

index4.jsp:

 
1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 5 <html>
 6 <head>
 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 8 <title>Insert title here</title>
 9 </head>
10 <body>
11
12 <c:set var="likes" value="Badminton,Photography,Music"></c:set>
13     <c:forTokens items="${likes }" delims="," var="myValue">
14         ${myValue }<br/>
15     </c:forTokens>
16 </body>
17 </html>
copy code

Line 12: The key of the string is likes, and the value is "Badminton, Photography, Music".

Line 13: Traverse the strings in items, the commas in delims are delimiters.

Run the program, the effect is as follows:

【Project Files】

Link: http://pan.baidu.com/s/1qWNU6Xe

Password: itqn

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325353798&siteId=291194637