Java初學者必學的JSTL

  所謂JSTL就是標籤庫  JSP Standard Tag Library,若是作爲java初學者你看不懂那些$符號的話,就有必要來了解一下JSTL,若是你看到滿眼的<%}%>(Scriptlet)以爲很糟心的話,那就更應該學學JSTL。css

   代碼分離一直是程序員所追求,框架的開發者天天都費盡心思想怎麼實現頁面和代碼分離,分離的好處好比:代碼清晰,美工和程序員不干擾,各作各的等。若是滿眼的<%%>就是滿眼的Java代碼,那就又都整合到一塊兒了。並且將代碼嵌入頁面,系統編譯運行時,很費時的,須要將頁面中的代碼轉換(HTML——JAVA),返回數據時還需轉換(JAVA——HTML),並且若是管理不善,很容易出事故的,因此儘可能使用JSTL就能提供一種善意的限制,何況用JSTL還能夠有效地提升系統速度了。特別是對於那些前臺開發人員,他們可能不懂Java,只是懂一些HTML和JSTL,那麼就能夠作出漂亮美觀的頁面,也不會受java或其餘語言的的困擾了,維護起來也比較簡單,這樣頁面和代碼分離了,角色分配也就更明顯了,整個團隊的合做也就更融洽了。就好比說我吧,剛學java,對java不是很熟悉,如今無心間被調到大系統裏作界面,只要我學習了標籤語言,就能很容易的將那些後臺程序員的結果顯示在個人頁面上,全部咱們就更有必要學習標籤庫了。html

 
  簡介:
    迭代和條件判斷
    數據管理格式化
    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.javajava

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>

 

效果:web

  

  
    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>

 

效果圖:apache

  

  經過上面的例子,JSTL也學習到了大部分了,但願之後的項目中多多運用,多多學習。編程

相關文章
相關標籤/搜索