JSTL 与 EL表达式

所谓JSTL就是标签库  JSP Standard Tag Library,如果做为java初学者你看不懂那些$符号的话,就有必要来了解一下JSTL,如果你看到满眼的<%}%>(Scriptlet)觉得很糟心的话,那就更应该学学JSTL。

   代码分离一直是程序员所追求,框架的开发者每天都费尽心思想怎么实现页面和代码分离,分离的好处比如:代码清晰,美工和程序员不干扰,各做各的等。如果满眼的<%%>就是满眼的Java代码,那就又都整合到一起了。而且将代码嵌入页面,系统编译运行时,很费时的,需要将页面中的代码转换(HTML——JAVA),返回数据时还需转换(JAVA——HTML),而且如果管理不善,很容易出事故的,所以尽量使用JSTL就能提供一种善意的限制,况且用JSTL还可以有效地提高系统速度了。特别是对于那些前台开发人员,他们可能不懂Java,只是懂一些HTML和JSTL,那么就可以做出漂亮美观的页面,也不会受java或其他语言的的困扰了,维护起来也比较简单,这样页面和代码分离了,角色分配也就更明显了,整个团队的合作也就更融洽了。就比如说我吧,刚学java,对java不是很熟悉,现在无意间被调到大系统里做界面,只要我学习了标签语言,就能很容易的将那些后台程序员的结果显示在我的页面上,所有我们就更有必要学习标签库了。

 
  简介:
    迭代和条件判断
    数据管理格式化
    XML操作
    数据库访问
    函数标签库
    表达式语言EL
   
  在学习JSTL之前要了解一下EL,它和标签库联合使用,就能避免在jsp里面出现大段的java代码段了。
  EL主要用于查找作用域中的数据,然后对它们执行简单操作;它不是编程语言,甚至不是脚本编制语言。通常与 JSTL 标记一起作用,能用简单而又方便的符号来表示复杂的行为。EL的格式就是一个美元符号加一对大括号---${}。
      如果只是使用EL表达式,不需要引用任何jar包。只要jsp/servlet容器实现了相关规范就可以了。
  下面是EL的举例应用:
  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>测试EL表达式</h1>
29   <hr>
30   <ul>
31       <li>普通字符串</li>
32       hello(jsp脚本):<%=request.getAttribute("hello") %> <br>
33       hellp(EL表达式:语法$和{}):${hello }<br>
34       hello(EL的内置对象:pageScope,requestScope,sessionScope,applicationScope)<br>
35       如果不指定范围,它的搜索顺序为:pageScope---applicationScope<br>
36       --------------举例----------------    <br>
37        ${requestScope.hello } <br>
38       ---------------------------------   <br>
39       hellp(EL表达式:指定范围从session中取得):值为“${sessionScope.hello } ”<br>
40       ***************************************************************************
41       <P>
42       <li>结构--->采用.进行导航,称为存取器</li><br>
43       姓名:${user.name }  --->规范是:name 前加get,name首写字母大写也就是调getName()方法<br>
44       年龄:${user.age }<br>
45       所属组:${user.group.name }<br>
46       ***************************************************************************
47       <p>
48       <li>map--->采用.进行导航,称为存取器</li><br>
49       map.key1:${map.key1 }  <br>
50       map.key2:${map.key2 }  <br>
51       ***************************************************************************
52       <p>
53       <li>字符串数组:------>采用[]下标</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>对象数组:------>采用[]下标</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:------>采用[]下标</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表达式对运算符的支持</li>
78       143+454=${143+454 }<br>
79 div 30=${150 div 30 }
80       ****************************************************************************
81       <p>
82       <li>测试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  * 测试EL表达式 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         //普通字符串
 53         request.setAttribute("hello", "hello world");
 54         
 55         //结构
 56         Group group=new Group();
 57         group.setName("提高班八期");
 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         //字符串数组
 73         String[] strArray=new String[]{"六期","七期","八期","九期","十期"};
 74         request.setAttribute("str_array", strArray);
 75         
 76         
 77         //对象数组
 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("提高班第"+i+"期");
 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", "提高班第八期");
100         request.setAttribute("tgb9", null);
101         //request的分发器
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  建立映射

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

效果:

EL表达式非常简单,只是一个${}就解决了,但是它的功能却非常单一,只能取得特定的某一个元素。如果想要遍历就不行了,再加上一些条件分支判断什么的也不行,也无法做到日期、数字等的格式化。所以要结合相应的标签来达到这样的效果。
     那么我们就需要一个标签库即JSTL。但是需要引入它的库,将jstl.jar和standard.jar考到WEB-INF/lib下,然后采用tablib指令引入标签库。
  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix ="c" %>

 

下面代码举例应用:

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>测试JSTL标签库</h1>
 31    <ul>
 32        <li>采用 c:out 标签</li>
 33        hello(使用标签):<c:out value="123"></c:out> <br>
 34        hello(使用标签,结合EL表达式):<c:out value="${hello }"></c:out><br>
 35        hello(使用EL表达式):${hello }<br>
 36        hello(使用EL表达式,default):${hello123 }<br>
 37        hello(使用标签,结合EL表达式,缺省值):<c:out value="${hello123 }" default="hello123"></c:out><br>
 38        hello(使用标签,结合EL表达式,缺省值):<c:out value="${hello123 }" >hello123</c:out><br>
 39       welcome(使用EL表达式):${welcome } <br>
 40       welcome(使用标签,escapeXml=true,EL表达式):<c:out value="${welcome }" escapeXml="true"></c:out> <br>
 41       welcome(使用标签,escapeXml=false,EL表达式):<c:out value="${welcome }" escapeXml="false"></c:out> <br>
 42       *********************************************
 43       <li>测试c:set 和 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>条件控制标签:--->c:if</li>
 50       <c:if test="${v1 lt v2 }">
 51           v1 小于v2 <br>
 52       </c:if>
 53       
 54       *********************************************
 55       <li>条件控制标签:c:choose,c:when,c:otherwise</li>
 56       <c:choose>
 57           <c:when test="${v1 gt v2 }">
 58               v1大于v2<br>
 59           </c:when>
 60           <c:otherwise>
 61               v1小于v2<br>
 62           </c:otherwise>
 63       </c:choose>
 64       
 65       <c:choose>
 66           
 67           <c:when test="${empty userList }">
 68           没有符合条件的数据<br>
 69           </c:when>
 70           <c:otherwise>
 71               存在用户数据<br>
 72           </c:otherwise>
 73       </c:choose>
 74       *********************************************
 75       <li>循环控制标签:--->c:forEach</li>
 76       <h3>采用jsp脚本显示</h3>
 77  
 78       <table border="1px">
 79           <tr>
 80               <td>用户姓名</td>
 81               <td>用户年龄</td>
 82               <td>所属组</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">没有符合条件的数据</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>采用c:forEach 标签</h3>
108       <table border="1px">
109           <tr>
110               <td>用户姓名</td>
111               <td>用户年龄</td>
112               <td>所属组</td>
113           </tr>
114           <c:choose>
115               <c:when test="${empty users }">
116               <tr>
117                   <td colspan="3">没有符合条件的数据</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>采用c:forEach ,varstatus</h3>
132       <table border="1px">
133           <tr>
134               <td>用户姓名</td>
135               <td>用户年龄</td>
136               <td>所属组</td>
137           </tr>
138           <c:choose>
139               <c:when test="${empty users }">
140                   <tr>
141                       <td colspan="3">没有符合条件的数据</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>循环控制标签forEach:输出map</li>
164       <c:forEach items="${map }" var="entry">
165           ${entry.key } ,${entry.value } <br>
166       </c:forEach>
167       <li>循环控制标签forTokens</li>
168       <c:forTokens items="${strTokens} " delims="#" var="v">
169           ${v } <br>
170       </c:forTokens>
171       <li>c:catch标签</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  * 演示JSTL核心库21  */
22 public class JstlCoreServlet extends HttpServlet {
23 
24     /**
25      * @author 巨亚红
26      * @date 2014-1-8 下午5:36:05
27      * @版本 V1.0   作者: 时间:  修改:
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         // 普通字符串
53         request.setAttribute("hello", "hello world");
54         
55         //HTML字符串
56         request.setAttribute("welcome", "<font color='red'>欢迎你来到这个世界</font>");
57     
58         //条件控制标签
59         request.setAttribute("v1", 10);
60         request.setAttribute("v2", 20);
61         
62         request.setAttribute("userList", new ArrayList());
63     
64         //结构
65             
66         
67         Group group = new Group();
68         group.setName("提高班第八期");
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>

效果图:

 

通过上面的例子,JSTL也学习到了大部分了,希望以后的项目中多多运用,多多学习。

注:转自http://www.cnblogs.com/jyh317/p/3514836.html


 

 

 

 

 

 

 

posted @ 2017-08-09 14:01  空涅  阅读(403)  评论(0编辑  收藏  举报