所謂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
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'jstl_el.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h1>測試EL表達式</h1> <hr> <ul> <li>普通字符串</li> hello(jsp腳本):<%=request.getAttribute("hello") %> <br> hellp(EL表達式:語法$和{}):${hello }<br> hello(EL的內置對象:pageScope,requestScope,sessionScope,applicationScope)<br> 如果不指定范圍,它的搜索順序為:pageScope---applicationScope<br> --------------舉例---------------- <br> ${requestScope.hello } <br> --------------------------------- <br> hellp(EL表達式:指定范圍從session中取得):值為“${sessionScope.hello } ”<br> *************************************************************************** <P> <li>結構--->采用.進行導航,稱為存取器</li><br> 姓名:${user.name } --->規范是:name 前加get,name首寫字母大寫也就是調getName()方法<br> 年齡:${user.age }<br> 所屬組:${user.group.name }<br> *************************************************************************** <p> <li>map--->采用.進行導航,稱為存取器</li><br> map.key1:${map.key1 } <br> map.key2:${map.key2 } <br> *************************************************************************** <p> <li>字符串數組:------>采用[]下標</li> <br> strArray[0]:${str_array[0]} <br> strArray[1]:${str_array[1]} <br> strArray[2]:${str_array[2]} <br> strArray[3]:${str_array[3]} <br> strArray[4]:${str_array[4]} <br> **************************************************************************** <p> <li>對象數組:------>采用[]下標</li> users[0]:${users[0].name } <br> users[1]:${users[1].name } <br> users[2]:${users[2].name } <br> users[3]:${users[3].name } <br> users[4]:${users[4].name } <br> **************************************************************************** <p> <li>list:------>采用[]下標</li> groupList[0].name:${groupList[0].name }<br> groupList[1].name:${groupList[1].name }<br> groupList[2].name:${groupList[2].name }<br> groupList[3].name:${groupList[3].name }<br> groupList[4].name:${groupList[4].name }<br> **************************************************************************** <p> <li>EL表達式對運算符的支持</li> 143+454=${143+454 }<br> 150 div 30=${150 div 30 } **************************************************************************** <p> <li>測試empty</li> tgb6:${empty tgb6 }<br> tgb7:${empty tgb7 }<br> tgb8:${empty tgb8 }<br> tgb9:${empty tgb9 }<br> </ul> </body> </html>
JstlElServlet.java
package com.tgb.jstl; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.sun.org.apache.bcel.internal.generic.NEW; /** * 測試EL表達式 * @author 巨亞紅 * @date 2014-1-7 下午6:26:20 * @版本 V1.0 作者: 時間: 修改: */ public class JstlElServlet extends HttpServlet { /** * Constructor of the object. */ public JstlElServlet() { super(); } /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //普通字符串 request.setAttribute("hello", "hello world"); //結構 Group group=new Group(); group.setName("提高班八期"); User user=new User(); user.setName("juyahong"); user.setAge(25); user.setGroup(group); request.setAttribute("user", user); //map Map map=new HashMap(); map.put("key1", "value1"); map.put("key2", "value2"); request.setAttribute("map", map); //字符串數組 String[] strArray=new String[]{"六期","七期","八期","九期","十期"}; request.setAttribute("str_array", strArray); //對象數組 User[] users=new User[5]; for (int i = 0; i < users.length; i++) { users[i]=new User(); users[i].setName("juyahong("+i+")"); } request.setAttribute("users", users); //list List groupList=new ArrayList(); for (int i = 6; i < 12; i++) { Group group2=new Group(); group2.setName("提高班第"+i+"期"); groupList.add(group2); } request.setAttribute("groupList", groupList); //empty request.setAttribute("tgb6", ""); request.setAttribute("tgb7", new ArrayList()); request.setAttribute("tgb8", "提高班第八期"); request.setAttribute("tgb9", null); //request的分發器 request.getRequestDispatcher("/jstl_el.jsp").forward(request, response); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
Group.java
package com.tgb.jstl; public class Group { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
User.java
package com.tgb.jstl; public class User { private String name; private int age; private Group group; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Group getGroup() { return group; } public void setGroup(Group group) { this.group = group; } }
web.xml 建立映射
<servlet> <servlet-name>JstlElServlet</servlet-name> <servlet-class>com.tgb.jstl.JstlElServlet</servlet-class> </servlet> <!-- 映射到servlet --> <servlet-mapping> <servlet-name>JstlElServlet</servlet-name> <url-pattern>/servlet/JstlElServlet</url-pattern> </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
<%@page import="javax.servlet.jsp.tagext.TryCatchFinally"%> <%@page import="com.tgb.jstl.User"%> <%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'jstl_core.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h1>測試JSTL標簽庫</h1> <ul> <li>采用 c:out 標簽</li> hello(使用標簽):<c:out value="123"></c:out> <br> hello(使用標簽,結合EL表達式):<c:out value="${hello }"></c:out><br> hello(使用EL表達式):${hello }<br> hello(使用EL表達式,default):${hello123 }<br> hello(使用標簽,結合EL表達式,缺省值):<c:out value="${hello123 }" default="hello123"></c:out><br> hello(使用標簽,結合EL表達式,缺省值):<c:out value="${hello123 }" >hello123</c:out><br> welcome(使用EL表達式):${welcome } <br> welcome(使用標簽,escapeXml=true,EL表達式):<c:out value="${welcome }" escapeXml="true"></c:out> <br> welcome(使用標簽,escapeXml=false,EL表達式):<c:out value="${welcome }" escapeXml="false"></c:out> <br> ********************************************* <li>測試c:set 和 c:remove</li> <c:set value="juyahong" var="userId"></c:set><br> userId:--->${userId } <br> <c:remove var="userId"/> <br> userId:--->${userId } <br> ********************************************* <li>條件控制標簽:--->c:if</li> <c:if test="${v1 lt v2 }"> v1 小於v2 <br> </c:if> ********************************************* <li>條件控制標簽:c:choose,c:when,c:otherwise</li> <c:choose> <c:when test="${v1 gt v2 }"> v1大於v2<br> </c:when> <c:otherwise> v1小於v2<br> </c:otherwise> </c:choose> <c:choose> <c:when test="${empty userList }"> 沒有符合條件的數據<br> </c:when> <c:otherwise> 存在用戶數據<br> </c:otherwise> </c:choose> ********************************************* <li>循環控制標簽:--->c:forEach</li> <h3>采用jsp腳本顯示</h3> <table border="1px"> <tr> <td>用戶姓名</td> <td>用戶年齡</td> <td>所屬組</td> </tr> <% List userList=(List)request.getAttribute("users"); if(userList == null || userList.size()==0){ %> <tr> <td colspan="3">沒有符合條件的數據</td> </tr> <% }else { for(Iterator iter=userList.iterator();iter.hasNext();){ User user=(User)iter.next(); %> <tr> <td><%=user.getName() %></td> <td><%=user.getAge() %></td> <td><%=user.getGroup().getName() %></td> </tr> <% } } %> </table> <h3>采用c:forEach 標簽</h3> <table border="1px"> <tr> <td>用戶姓名</td> <td>用戶年齡</td> <td>所屬組</td> </tr> <c:choose> <c:when test="${empty users }"> <tr> <td colspan="3">沒有符合條件的數據</td> </tr> </c:when> <c:otherwise> <c:forEach items="${users }" var="user"> <tr> <td>${user.name }</td> <td>${user.age }</td> <td>${user.group.name }</td> </tr> </c:forEach> </c:otherwise> </c:choose> </table> <h3>采用c:forEach ,varstatus</h3> <table border="1px"> <tr> <td>用戶姓名</td> <td>用戶年齡</td> <td>所屬組</td> </tr> <c:choose> <c:when test="${empty users }"> <tr> <td colspan="3">沒有符合條件的數據</td> </tr> </c:when> <c:otherwise> <c:forEach items="${users }" var="user" varStatus="vs"> <c:choose> <c:when test="${vs.count mod 2==0 }"> <tr bgcolor="red"> </c:when> <c:otherwise> <tr> </c:otherwise> </c:choose> <td>${user.name }</td> <td>${user.age }</td> <td>${user.group.name }</td> </tr> </c:forEach> </c:otherwise> </c:choose> </table> <li>循環控制標簽forEach:輸出map</li> <c:forEach items="${map }" var="entry"> ${entry.key } ,${entry.value } <br> </c:forEach> <li>循環控制標簽forTokens</li> <c:forTokens items="${strTokens} " delims="#" var="v"> ${v } <br> </c:forTokens> <li>c:catch標簽</li> <p> <% try{ Integer.parseInt("ahkjdhfjk"); } catch(Exception e){ out.println(e.getMessage()); } %> </p> <P> <c:catch var="msg"> <% Integer.parseInt("ahkjdhfjk"); %> </c:catch> ${msg } </P> </ul> </body> </html>
JstlCoreServlet.java
package com.tgb.jstl; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 演示JSTL核心庫 * @author 巨亞紅 * @date 2014-1-7 下午9:19:15 * @版本 V1.0 作者: 時間: 修改: */ public class JstlCoreServlet extends HttpServlet { /** * @author 巨亞紅 * @date 2014-1-8 下午5:36:05 * @版本 V1.0 作者: 時間: 修改: */ private static final long serialVersionUID = 1L; /** * Constructor of the object. */ public JstlCoreServlet() { super(); } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 普通字符串 request.setAttribute("hello", "hello world"); //HTML字符串 request.setAttribute("welcome", "<font color='red'>歡迎你來到這個世界</font>"); //條件控制標簽 request.setAttribute("v1", 10); request.setAttribute("v2", 20); request.setAttribute("userList", new ArrayList()); //結構 Group group = new Group(); group.setName("提高班第八期"); List users = new ArrayList(); for (int i=0; i<10; i++) { User user = new User(); user.setName("juyahong(" + i+")"); user.setAge(23 + i); user.setGroup(group); users.add(user); } request.setAttribute("users", users); //map Map map=new HashMap(); map.put("key1", "value1"); map.put("key2", "value2"); map.put("key3", "value3"); map.put("key4", "value4"); request.setAttribute("map", map); //forTokens request.setAttribute("strTokens", "1#2#3#4#5"); request.getRequestDispatcher("/jstl_core.jsp").forward(request, response); } }
web.xml
<servlet> <servlet-name>JstlCoreServlet</servlet-name> <servlet-class>com.tgb.jstl.JstlCoreServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>JstlCoreServlet</servlet-name> <url-pattern>/servlet/JstlCoreServlet</url-pattern> </servlet-mapping>
效果圖:
通過上面的例子,JSTL也學習到了大部分了,希望以后的項目中多多運用,多多學習。