JSTL and EL Expressions

Keywords: Java JSP xml less

The so-called JSTL is the tag library JSP Standard Tag Library. If you are a java beginner and don't understand those $symbols, it's necessary to know JSTL. If you see <%}%> (Scriptlet) full of eyes and feel bad, you should learn JSTL.

Code separation has always been a pursuit of programmers. Framework developers are working hard every day to think about how to achieve page and code separation. The benefits of separation include code clarity, no interference from artists and programmers, and doing everything individually.If full-eye <%> is full-eye Java code, it's all integrated again.Moreover, embedding code into pages requires time-consuming code conversion (HTML - JAVA) in the pages, conversion (JAVA - HTML) in the return of data, and accident prone if poorly managed, so using JSTL as much as possible can provide a kind of limitation, and using JSTL can also effectively improve system speed.Especially for front-end developers, they may not know Java, they just know some HTML and JSTL, so they can make beautiful pages, they won't be confused by Java or other languages, and they are easy to maintain, so that the pages and code are separated, the role assignment is more obvious, and the whole team will work better together.For example, I just learned java, I am not familiar with java, and now I am unintentionally transferred to a large system to do interface. As long as I learn the label language, it is easy to display the results of those background programmers on my page, so it is more necessary for us to learn the label library.

 
Introduction:
Iteration and conditional judgment
Data management formatting
* XML operations
* Database Access
Function Label Library
* Expression Language EL
   
Before learning JSTL, learn about EL, which works in conjunction with tag libraries to avoid large java snippets in a jsp.
EL is primarily used to find data in a scope and then perform simple operations on them; it is not a programming language or even a scripting language.Usually used in conjunction with JSTL tags, complex behaviors can be represented with simple and convenient symbols.EL is formatted as a dollar sign with a pair of braces - ${}.
If you are only using EL expressions, you do not need to reference any jar packages.As long as the jsp/servlet container implements the relevant specifications.
The following are examples of EL applications:
  jstl_el.jsp
 1 <%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
 2 
 3 
 4 <%
 5 String path = request.getContextPath();
 6 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 7 %>
 8 
 9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
10 <html>
11   <head>
12     <base href="<%=basePath%>">
13     
14     <title>My JSP 'jstl_el.jsp' starting page</title>
15     
16     <meta http-equiv="pragma" content="no-cache">
17     <meta http-equiv="cache-control" content="no-cache">
18     <meta http-equiv="expires" content="0">    
19     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
20     <meta http-equiv="description" content="This is my page">
21     <!--
22     <link rel="stylesheet" type="text/css" href="styles.css">
23     -->
24 
25   </head>
26   
27   <body>
28   <h1>test EL Expression</h1>
29   <hr>
30   <ul>
31       <li>Normal String</li>
32       hello(jsp Script:<%=request.getAttribute("hello") %> <br>
33       hellp(EL Expression: Grammar $and{}): ${hello }<br>
34       hello(EL Built-in objects: pageScope,requestScope,sessionScope,applicationScope)<br>
35       If you do not specify a range, its search order is: pageScope---applicationScope<br>
36       --------------Give an example----------------    <br>
37        ${requestScope.hello } <br>
38       ---------------------------------   <br>
39       hellp(EL Expression: Specifies that the range from session Obtained in): The value is " ${sessionScope.hello } "<br>
40       ***************************************************************************
41       <P>
42       <li>structure--->Use.Navigate, called an accessor</li><br>
43       Full name: ${user.name }  --->The specification is: name preposed get,name Initial capitals are intonations getName()Method<br>
44       Age: ${user.age }<br>
45       Group to which: ${user.group.name }<br>
46       ***************************************************************************
47       <p>
48       <li>map--->Use.Navigate, called an accessor</li><br>
49       map.key1:${map.key1 }  <br>
50       map.key2:${map.key2 }  <br>
51       ***************************************************************************
52       <p>
53       <li>String Array:------>Use[]subscript</li> <br>
54       strArray[0]:${str_array[0]} <br>
55       strArray[1]:${str_array[1]} <br>
56       strArray[2]:${str_array[2]} <br>
57       strArray[3]:${str_array[3]} <br>
58       strArray[4]:${str_array[4]} <br>  
59       ****************************************************************************
60       <p>
61       <li>object array:------>Use[]subscript</li>
62       users[0]:${users[0].name } <br>
63       users[1]:${users[1].name } <br>
64       users[2]:${users[2].name } <br>
65       users[3]:${users[3].name } <br>
66       users[4]:${users[4].name } <br>
67     ****************************************************************************
68       <p>
69       <li>list:------>Use[]subscript</li>
70       groupList[0].name:${groupList[0].name }<br>
71       groupList[1].name:${groupList[1].name }<br>
72       groupList[2].name:${groupList[2].name }<br>
73       groupList[3].name:${groupList[3].name }<br>
74       groupList[4].name:${groupList[4].name }<br>
75       ****************************************************************************
76       <p>
77       <li>EL Expression support for operators</li>
78       143+454=${143+454 }<br>
79 div 30=${150 div 30 }
80       ****************************************************************************
81       <p>
82       <li>test empty</li>
83       tgb6:${empty tgb6 }<br>
84       tgb7:${empty tgb7 }<br>
85       tgb8:${empty tgb8 }<br>
86       tgb9:${empty tgb9 }<br>
87       
88       
89   </ul>
90   </body>
91 </html>
JstlElServlet.java
  1 package com.tgb.jstl;
  2 
  3 import java.io.IOException;
  4 import java.io.PrintWriter;
  5 import java.util.ArrayList;
  6 import java.util.HashMap;
  7 import java.util.List;
  8 import java.util.Map;
  9 
 10 import javax.servlet.ServletException;
 11 import javax.servlet.http.HttpServlet;
 12 import javax.servlet.http.HttpServletRequest;
 13 import javax.servlet.http.HttpServletResponse;
 14 
 15 import com.sun.org.apache.bcel.internal.generic.NEW;
 16 
 17 /**
 18  * Test EL expression 22  */
 23 public class JstlElServlet extends HttpServlet {
 24 
 25     /**
 26      * Constructor of the object.
 27      */
 28     public JstlElServlet() {
 29         super();
 30     }
 31 
 32     /**
 33      * Destruction of the servlet. <br>
 34      */
 35     public void destroy() {
 36         super.destroy(); // Just puts "destroy" string in log
 37         // Put your code here
 38     }
 39 
 40     /**
 41      * The doGet method of the servlet. <br>
 42      *
 43      * This method is called when a form has its tag value method equals to get.
 44      * 
 45      * @param request the request send by the client to the server
 46      * @param response the response send by the server to the client
 47      * @throws ServletException if an error occurred
 48      * @throws IOException if an error occurred
 49      */
 50     public void doGet(HttpServletRequest request, HttpServletResponse response)
 51             throws ServletException, IOException {
 52         //Normal String
 53         request.setAttribute("hello", "hello world");
 54         
 55         //structure
 56         Group group=new Group();
 57         group.setName("Increase Class Eight");
 58         
 59         User user=new User();
 60         user.setName("juyahong");
 61         user.setAge(25);
 62         user.setGroup(group);
 63         request.setAttribute("user", user);
 64         
 65         
 66         //map
 67         Map map=new HashMap();
 68         map.put("key1", "value1");
 69         map.put("key2", "value2");
 70         request.setAttribute("map", map);
 71         
 72         //String Array
 73         String[] strArray=new String[]{"Phase VI","Seven Periods","Phase VIII","Phase 9","Phase 10"};
 74         request.setAttribute("str_array", strArray);
 75         
 76         
 77         //object array
 78         User[] users=new User[5];
 79         for (int i = 0; i < users.length; i++) {
 80             users[i]=new User();
 81             users[i].setName("juyahong("+i+")");
 82         }
 83         request.setAttribute("users", users);
 84         
 85         
 86         //list
 87         List groupList=new ArrayList();
 88         for (int i = 6; i < 12; i++) {
 89             Group group2=new Group();
 90             group2.setName("Increase Class"+i+"stage");
 91             groupList.add(group2);
 92         }
 93         request.setAttribute("groupList", groupList);
 94         
 95         
 96         //empty
 97         request.setAttribute("tgb6", "");
 98         request.setAttribute("tgb7", new ArrayList());
 99         request.setAttribute("tgb8", "Increase Class Eighth");
100         request.setAttribute("tgb9", null);
101         //request Distributor
102         request.getRequestDispatcher("/jstl_el.jsp").forward(request, response);
103         
104     }
105 
106     /**
107      * The doPost method of the servlet. <br>
108      *
109      * This method is called when a form has its tag value method equals to post.
110      * 
111      * @param request the request send by the client to the server
112      * @param response the response send by the server to the client
113      * @throws ServletException if an error occurred
114      * @throws IOException if an error occurred
115      */
116     public void doPost(HttpServletRequest request, HttpServletResponse response)
117             throws ServletException, IOException {
118 
119         response.setContentType("text/html");
120         PrintWriter out = response.getWriter();
121         out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
122         out.println("<HTML>");
123         out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
124         out.println("  <BODY>");
125         out.print("    This is ");
126         out.print(this.getClass());
127         out.println(", using the POST method");
128         out.println("  </BODY>");
129         out.println("</HTML>");
130         out.flush();
131         out.close();
132     }
133 
134     /**
135      * Initialization of the servlet. <br>
136      *
137      * @throws ServletException if an error occurs
138      */
139     public void init() throws ServletException {
140         // Put your code here
141     }
142 
143 }

Group.java

 1 package com.tgb.jstl;
 2 
 3 public class Group {
 4     private String name;
 5 
 6     public String getName() {
 7         return name;
 8     }
 9 
10     public void setName(String name) {
11         this.name = name;
12     }
13     
14 }

User.java

 1 package com.tgb.jstl;
 2 
 3 public class User {
 4     private String name;
 5     private int age;
 6     private Group group;
 7     public String getName() {
 8         return name;
 9     }
10     public void setName(String name) {
11         this.name = name;
12     }
13     public int getAge() {
14         return age;
15     }
16     public void setAge(int age) {
17         this.age = age;
18     }
19     public Group getGroup() {
20         return group;
21     }
22     public void setGroup(Group group) {
23         this.group = group;
24     }
25     
26 }

web.xml Mapping

1 <servlet>
2     <servlet-name>JstlElServlet</servlet-name>
3     <servlet-class>com.tgb.jstl.JstlElServlet</servlet-class>
4   </servlet>
5 <!-- Map to servlet -->
6 <servlet-mapping>
7     <servlet-name>JstlElServlet</servlet-name>
8     <url-pattern>/servlet/JstlElServlet</url-pattern>
9 </servlet-mapping>

Effect:

EL expression is very simple, only a ${} solves it, but its function is very simple, can only get a specific element.If you want to traverse it will not work, plus some conditional branches to determine nothing, and you will not be able to format dates, numbers, and so on.So combine the corresponding tags to achieve this effect.
Then we need a tag library, JSTL.However, you need to import its library, take jstl.jar and standard.jar into WEB-INF/lib, and then use the tablib directive to import the label library.
  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix ="c" %>

 

The following code is used as an example:

jstl_core.jsp
  1 <%@page import="javax.servlet.jsp.tagext.TryCatchFinally"%>
  2 <%@page import="com.tgb.jstl.User"%>
  3 <%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
  4 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  5 
  6 <%
  7 String path = request.getContextPath();
  8 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  9 %>
 10 
 11 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 12 <html>
 13   <head>
 14     <base href="<%=basePath%>">
 15     
 16     <title>My JSP 'jstl_core.jsp' starting page</title>
 17     
 18     <meta http-equiv="pragma" content="no-cache">
 19     <meta http-equiv="cache-control" content="no-cache">
 20     <meta http-equiv="expires" content="0">    
 21     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 22     <meta http-equiv="description" content="This is my page">
 23     <!--
 24     <link rel="stylesheet" type="text/css" href="styles.css">
 25     -->
 26 
 27   </head>
 28   
 29   <body>
 30    <h1>test JSTL Label Library</h1>
 31    <ul>
 32        <li>Use c:out Label</li>
 33        hello(Use labels): <c:out value="123"></c:out> <br>
 34        hello(Use labels, combine EL Expression): <c:out value="${hello }"></c:out><br>
 35        hello(Use EL Expression): ${hello }<br>
 36        hello(Use EL Expression,default): ${hello123 }<br>
 37        hello(Use labels, combine EL Expression,Default value): <c:out value="${hello123 }" default="hello123"></c:out><br>
 38        hello(Use labels, combine EL Expression,Default value): <c:out value="${hello123 }" >hello123</c:out><br>
 39       welcome(Use EL Expression): ${welcome } <br>
 40       welcome(Use labels,escapeXml=true,EL Expression):<c:out value="${welcome }" escapeXml="true"></c:out> <br>
 41       welcome(Use labels,escapeXml=false,EL Expression):<c:out value="${welcome }" escapeXml="false"></c:out> <br>
 42       *********************************************
 43       <li>test c:set and c:remove</li>
 44       <c:set value="juyahong" var="userId"></c:set><br>
 45       userId:--->${userId } <br>
 46       <c:remove var="userId"/> <br>
 47       userId:--->${userId } <br>
 48       *********************************************
 49       <li>Conditional control label:--->c:if</li>
 50       <c:if test="${v1 lt v2 }">
 51           v1 less than v2 <br>
 52       </c:if>
 53       
 54       *********************************************
 55       <li>Conditional control label: c:choose,c:when,c:otherwise</li>
 56       <c:choose>
 57           <c:when test="${v1 gt v2 }">
 58               v1 greater than v2<br>
 59           </c:when>
 60           <c:otherwise>
 61               v1 less than v2<br>
 62           </c:otherwise>
 63       </c:choose>
 64       
 65       <c:choose>
 66           
 67           <c:when test="${empty userList }">
 68           No eligible data<br>
 69           </c:when>
 70           <c:otherwise>
 71               User data present<br>
 72           </c:otherwise>
 73       </c:choose>
 74       *********************************************
 75       <li>Loop control label:--->c:forEach</li>
 76       <h3>Use jsp Script Display</h3>
 77  
 78       <table border="1px">
 79           <tr>
 80               <td>User Name</td>
 81               <td>User Age</td>
 82               <td>Group to which you belong</td>
 83           </tr>
 84           <%
 85               List userList=(List)request.getAttribute("users");
 86               if(userList == null || userList.size()==0){
 87           %>
 88               <tr>
 89                   <td colspan="3">No eligible data</td>
 90               </tr>
 91           <% 
 92               }else {
 93               for(Iterator iter=userList.iterator();iter.hasNext();){
 94                    User user=(User)iter.next();
 95            %>
 96                    <tr>
 97                        <td><%=user.getName() %></td>
 98                        <td><%=user.getAge() %></td>
 99                        <td><%=user.getGroup().getName() %></td>
100                    </tr>
101            
102            <%
103                    }
104                  }
105             %>
106       </table>
107       <h3>Use c:forEach Label</h3>
108       <table border="1px">
109           <tr>
110               <td>User Name</td>
111               <td>User Age</td>
112               <td>Group to which you belong</td>
113           </tr>
114           <c:choose>
115               <c:when test="${empty users }">
116               <tr>
117                   <td colspan="3">No eligible data</td>
118               </tr>
119               </c:when>
120               <c:otherwise>
121                   <c:forEach items="${users }" var="user">
122                       <tr>
123                           <td>${user.name }</td>
124                           <td>${user.age }</td>
125                           <td>${user.group.name }</td>
126                       </tr>
127                   </c:forEach>
128               </c:otherwise>
129           </c:choose>
130       </table>
131       <h3>Use c:forEach ,varstatus</h3>
132       <table border="1px">
133           <tr>
134               <td>User Name</td>
135               <td>User Age</td>
136               <td>Group to which you belong</td>
137           </tr>
138           <c:choose>
139               <c:when test="${empty users }">
140                   <tr>
141                       <td colspan="3">No eligible data</td>
142                   </tr>
143               </c:when>
144               <c:otherwise>
145                   <c:forEach items="${users }" var="user" varStatus="vs">
146                       <c:choose>
147                           <c:when test="${vs.count mod 2==0 }">
148                               <tr bgcolor="red">
149                           </c:when>
150                           <c:otherwise>
151                               <tr>
152                           </c:otherwise>
153                       </c:choose>
154                                   <td>${user.name }</td>
155                                   <td>${user.age }</td>
156                                   <td>${user.group.name }</td>
157                               </tr>
158                   </c:forEach>
159               
160               </c:otherwise>
161           </c:choose>
162       </table>
163       <li>Loop Control Label forEach: output map</li>
164       <c:forEach items="${map }" var="entry">
165           ${entry.key } ,${entry.value } <br>
166       </c:forEach>
167       <li>Loop Control Label forTokens</li>
168       <c:forTokens items="${strTokens} " delims="#" var="v">
169           ${v } <br>
170       </c:forTokens>
171       <li>c:catch Label</li>
172   <p>
173       <%
174           try{
175               Integer.parseInt("ahkjdhfjk");
176           } catch(Exception e){
177               out.println(e.getMessage());
178           }
179        %>
180   </p>
181   <P>
182       <c:catch var="msg">
183           <%
184           Integer.parseInt("ahkjdhfjk");
185            %>
186       </c:catch>
187       ${msg }
188   </P>
189       
190    </ul>
191   </body>
192 </html>
JstlCoreServlet.java
 1 package com.tgb.jstl;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 import java.util.ArrayList;
 6 import java.util.HashMap;
 7 import java.util.List;
 8 import java.util.Map;
 9 
10 import javax.servlet.ServletException;
11 import javax.servlet.http.HttpServlet;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14 
15 
16 /**
17  * Demonstrate JSTL Core Library21  */
22 public class JstlCoreServlet extends HttpServlet {
23 
24     /**
25      * @author Giant Subred
26      * @date 2014-1-8 5:36:05 p.m.
27      * @Version V1.0 Author: Time: Modification:
28      */
29     private static final long serialVersionUID = 1L;
30     /**
31      * Constructor of the object.
32      */
33     public JstlCoreServlet() {
34         super();
35     }
36 
37     
38 
39     /**
40      * The doGet method of the servlet. <br>
41      *
42      * This method is called when a form has its tag value method equals to get.
43      * 
44      * @param request the request send by the client to the server
45      * @param response the response send by the server to the client
46      * @throws ServletException if an error occurred
47      * @throws IOException if an error occurred
48      */
49     public void doGet(HttpServletRequest request, HttpServletResponse response)
50             throws ServletException, IOException {
51 
52         // Normal String
53         request.setAttribute("hello", "hello world");
54         
55         //HTML Character string
56         request.setAttribute("welcome", "<font color='red'>Welcome to this world</font>");
57     
58         //Conditional control label
59         request.setAttribute("v1", 10);
60         request.setAttribute("v2", 20);
61         
62         request.setAttribute("userList", new ArrayList());
63     
64         //structure
65             
66         
67         Group group = new Group();
68         group.setName("Increase Class Eighth");
69                 
70         List users = new ArrayList();
71         for (int i=0; i<10; i++) {
72                 User user = new User();
73                 user.setName("juyahong(" + i+")");
74                 user.setAge(23 + i);
75                 user.setGroup(group);
76                 users.add(user);
77         }
78         request.setAttribute("users", users);
79         
80         
81         //map
82         Map map=new HashMap();
83         map.put("key1", "value1");
84         map.put("key2", "value2");
85         map.put("key3", "value3");
86         map.put("key4", "value4");
87         request.setAttribute("map", map);
88         
89         
90         //forTokens
91         request.setAttribute("strTokens", "1#2#3#4#5");
92         
93         request.getRequestDispatcher("/jstl_core.jsp").forward(request, response);
94         
95     }
96 }

web.xml

1 <servlet>
2     <servlet-name>JstlCoreServlet</servlet-name>
3     <servlet-class>com.tgb.jstl.JstlCoreServlet</servlet-class>
4   </servlet>
5 <servlet-mapping>
6     <servlet-name>JstlCoreServlet</servlet-name>
7     <url-pattern>/servlet/JstlCoreServlet</url-pattern>
8   </servlet-mapping>

Design sketch:

 

Through the above examples, JSTL has also learned most of them. I hope to use more and learn more in future projects.

Note: From http://www.cnblogs.com/jyh317/p/3514836.html


 

 

 

 

 

 

 

Posted by RHolm on Thu, 06 Jun 2019 10:23:34 -0700