JavaEE學習day-52:EL表達式和JSTL標簽

一、EL表達式

1.EL表達式的概念:

  • 傳統(tǒng)方式在jsp中獲取數據的弊端

使用腳本段語句獲取作用域中的數據的缺陷,書寫比較繁瑣;需要導包;需要強轉。

  • EL表達式的作用:

讓 jsp 書寫起來更加的方便。簡化在 jsp 中獲取作用域或者請求數據的寫法。也會搭配 Jstl 來進行使用。

2.EL表達式獲取請求頭數據:

(1)${header} 返回所有的請求頭數據,鍵值對形式。

(2)${header["鍵名"]} 返回指定的鍵的請求頭數據。

(3)${headerValues["鍵名"]}。

3.EL表達式獲取Cookie數據:

(1)${cookie} 獲取所有的Cookie對象 鍵值對。

(2)${cookie.Cookie對象的鍵名} 獲取存儲了指定Cookie數據的Cookie對象。

(3)${cookie.Cookie對象的鍵名.name}:獲取存儲了指定Cookie數據的Cookie對象的存儲的鍵。

(4)${cookie.Cookie對象的鍵名.value}獲取存儲了指定Cookie數據的Cookie對象的存儲的值。

<h3>獲取Cookie數據</h3>
${cookie} <br />
${cookie.JSESSIONID} <br />
${cookie.JSESSIONID.name}--${cookie.JSESSIONID.value}

4.獲取請求實體數據:

(1)${param.鍵名}:獲取請求實體中一個鍵一個值的數據。

(2)${paramValues.鍵名}:獲取請求實體中同鍵不同值的數據,返回的是String數組,可以使用角標直接獲取。

<h3>獲取用戶請求數據(請求實體)</h3>
<%=request.getParameter("uname") %>--${param.uname} <br />
<%=request.getParameterValues("fav")[1] %>--${paramValues.fav[1]}

5.EL表達式獲取作用域數據:

(1)獲取作用域字符串數據的格式:${鍵名};

(2)獲取作用域對象數據的格式:${鍵名.屬性名};

(3)獲取List集合和Map集合的數據的格式:

List:${鍵名[角標]}。

Map:${map集合作用域存儲的鍵名.map集合存儲的數據的鍵名}。

(4)獲取指定作用域數據的格式:

${pageScope.鍵名}:指明獲取pageContext作用域中的數據。

${requestScope.鍵名}:指明獲取request作用域中的數據。

${sessionScope.鍵名}:指明獲取session作用域中的數據。

${applicationScope.鍵名}:指明獲取application作用域中的數據。

(5)EL獲取指定作用域數據的查找順序:

pageContext-->request-->session-->application;

<h3>EL獲取作用域數據時作用域的查找順序</h3>
<%
    pageContext.setAttribute("hello", "hello pageContext");
    request.setAttribute("hello","hello request");
    session.setAttribute("hello", "hello session");
    application.setAttribute("hello", "hello application");
%>
${requestScope.hello}--${a}

6.EL表達式中的運算和empty判斷:

(1)算術運算:和普通的加減乘除沒什么區(qū)別;
(2)邏輯運算:EL中只有&&和||沒有&和|。
(3)empty的作用:

作用:判斷該鍵是否有存儲有效數據。
使用格式:${empty 鍵名};

<h3>EL表達式的empty判斷</h3>
<%
    request.setAttribute("str","");
    User u=new User();
    request.setAttribute("u", u);
    ArrayList la=new ArrayList();
    request.setAttribute("la",la);

%>
${empty str}<br />
${empty u}<br />
${empty la}<br />

二、JSTL

1.JSTL的概念:

  • jstl的作用:

用來提升在 JSP 頁面的邏輯代碼的編碼效率,使用標簽來替換邏輯代碼的直接書寫,高效,美觀,整潔,易讀。

  • 使用流程:

(1)導包。
(2)使用 taglib 標簽引入資源。
(3)使用jsit的核心標簽。

  • 引入JSTL:

引入資源<%@tagliburi="http://java.sun.com/jsp/jstl/core"prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>

2.核心標簽:

  • out標簽:

使用格式:<c:out value="${表達式}" default="默認值"></c:out>;
作用:結合EL表達式將數據響應給瀏覽器,如果EL表達式沒有取到數據則可以使用default屬性聲明默認值。

  • set標簽:

使用格式:set標簽: <c:set value="數據" var="鍵名" scope="作用域名"></c:set>;
作用:將數據存儲到指定的作用域中,默認是pageContext作用域。

  • remove標簽:

使用格式:<c:remove var="要刪除數據的鍵名" scope="作用域名"/>;
作用:刪除作用域中的數據,默認是刪除四個作用域中的符合要求的數據。

  • 注意使用remove:

(1)使用pageContext.removeAttriute("鍵名"),此方法會將四個作用域中的符合要求的數據全部刪除。
(2)使用pageContext.removeAttriute(String name,int scope)指明要刪除的作用域中的數據 scope的值為 1pageContext,2request ,3 session,4 application。
(3)使用request.removeAttibute("鍵名"):刪除當前作用域符合要求的數據。
(4)使用session.removeAttibute("鍵名"):刪除當前作用域符合要求的數據。
(5)使用application.removeAttibute("鍵名"):刪除當前作用域符合要求的數據。

<%
    request.setAttribute("str","jstl學習");
 %>
 <!-- out標簽學習 -->
 <%=request.getAttribute("str") %>--${str}--<c:out value="${str}" default="我是out標簽"></c:out>
 <br />
 <!-- set標簽學習 -->
 <%
    request.setAttribute("s1","set標簽學習");
    
 %>
 <c:set value="set標簽學習2" var="s2" scope="request"></c:set>
 <c:set value="hello pageContext" var="hello" scope="page"></c:set>
 <c:set value="hello request" var="hello" scope="request"></c:set>
 <c:set value="hello session" var="hello" scope="session"></c:set>
 <c:set value="hello application" var="hello" scope="application"></c:set>
 ${s1}--${requestScope.s2}
 <br />
 <!-- remove標簽學習 -->
<%-- <%
    pageContext.removeAttribute("hello",4);
    //request.removeAttribute("hello");
    //session.removeAttribute("hello");
 %>  --%>
<c:remove var="hello" scope="request"/>
${hello}

3.if和choose標簽:

  • if標簽:

使用格式:<c:if test="${表達式}">數據</c:if>;
作用:可以根據el表達式進行一定程度的單分支邏輯判斷。

  • 注意:

test屬性中書寫的是EL表達式,或者說是EL表達式的邏輯表達式。該標簽只能進行EL表達式相關的邏輯判斷。不能進行EL表達式不能獲取的數據的邏輯處理。

<c:set var="a" value="12"></c:set>
<%
    int b=4;
    int a=Integer.parseInt((String)pageContext.getAttribute("a"));
    if(a>8){
%>
    <b>今天天氣真好,適合學習1</b>
<%} %>
<c:if test="${a>8}">
    <b>今天天氣真好,適合學習2</b>
</c:if>
  • choose標簽:

<c:choose>
<c:when test="${表達式}"></c:when>

<c:when test="${表達式}"></c:when>
..
<c:otherwise></c:otherwise>
</c:choose>
作用:類似于switch-case。

  • 注意:

符合條件后只會執(zhí)行一個分支,其他分支不會執(zhí)行。

<!--多分支邏輯判斷  -->
<c:set var="score" value="40"></c:set>
<c:choose>
    <c:when test="${score>=90}">
        <i>獎勵蘋果電腦一臺</i>
    </c:when>
    <c:when test="${score<90&&score>=80}">
        <i>獎勵蘋果手機一部</i>
    </c:when>
    <c:when test="${score>=70&&score<80}">
        <i>無獎勵無懲罰</i>
    </c:when>
    <c:otherwise>
        <i>男女混合雙打</i>
    </c:otherwise>
</c:choose>

4.foreach循環(huán)標簽:

  • foreach標簽:

格式:<c:foreach>循環(huán)體</c:foreach>

  • foreach中的屬性:

(1)begin:聲明循環(huán)的開始位置。
(2)end:聲明循環(huán)的結束位置。
(3)step:聲明循環(huán)的步長。
(4)varStatus:聲明變量記錄循環(huán)狀態(tài)。
(5)items:聲明要遍歷的數據,可以是集合和數組等。
(6)var:聲明變量記錄每次遍歷的結果。可以做循環(huán)體中使用使用EL表達式獲取遍歷出來的數據。

  • varStatus屬性獲取循環(huán)狀態(tài):

(1)${i.index}獲取當次循環(huán)的下標。

(2)${i.count}獲取當次循環(huán)的次數。

(3)${i.first}判斷是否是第一次循環(huán)。

(4)${i.last}判斷是否是最后一次循環(huán)。

<c:forEach begin="0" end="5" step="1" varStatus="i">
    <c:if test="${i.count==3}">
        <u>我是第三次循環(huán)</u>
    </c:if>
    11111--${i.index}--${i.count}--${i.first}--${i.last}<br />
</c:forEach>

  • 遍歷Map和List
<!-- 遍歷List集合 -->
<%
    //創(chuàng)建測試數據list
    ArrayList<String> list=new ArrayList<String>();
    list.add("蘋果");
    list.add("榴蓮");
    list.add("荔枝");
    //將list存儲到作用域中
    request.setAttribute("list",list);
    
%>
<c:forEach items="${list}" var="s" varStatus="i">
    ${s}--${i.index}--${i.count}<br />
</c:forEach>
<!--遍歷map集合  -->
<%
    //聲明Map集合測試數據
    HashMap<String,String> hs=new HashMap<String ,String>();
    hs.put("s1","唱歌");
    hs.put("s2", "跳舞");
    hs.put("s3", "敲代碼");
    //將數據存儲到作用域中
    request.setAttribute("hs", hs);
%>
<c:forEach items="${hs}" var="s">
    ${s.key}--${s.value}<br />
</c:forEach>

三、使用JSTL修改項目為項目增添查詢用戶信息功能

1.增添查詢用戶信息功能

  • 添加查詢所用用戶的信息:
/**
     * 用戶查詢
     */
    @Override
    public List<User> selUserInfoDao() {
        //聲明jdbc變量
        Connection conn=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        List<User> list = null;
        
                try {
                    //創(chuàng)建連接
                    conn = DBUtil.getConnection();
                    //創(chuàng)建sql語句
                    String sql="select * from t_user";
                    //創(chuàng)建slq命令對象
                    ps=conn.prepareStatement(sql);
                    //執(zhí)行sql命令
                    rs = ps.executeQuery();
                    list = new ArrayList<User>();
                    //遍歷rs
                    while(rs.next()){
                        //給變量賦值
                        User us=new User();
                        us.setUid(rs.getInt("uid"));
                        us.setUname(rs.getString("uname"));
                        us.setPwd(rs.getString("pwd"));
                        us.setSex(rs.getString("sex"));
                        us.setAge(rs.getInt("age"));
                        us.setBirthday(rs.getString("birthday"));
                        list.add(us);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }finally{
                    DBUtil.closeAll(rs, ps, conn);
                    
                }
                return list;
   }
  • 在DataServlet中增加查詢用戶信息方法:
//查詢用戶信息
    public void selUserInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        //獲取請求信息
        //處理請求信息
            //創(chuàng)建業(yè)務層對象
            UserService us = new UserServiceImpl();
            //調用業(yè)務層方法
            List<User> lu = us.selUserInfoService();
            //響應處理結果
                //將結果存儲到request作用域中
            request.setAttribute("lu", lu);
            //請求轉發(fā)
            request.getRequestDispatcher("user/userList2.jsp").forward(request, response);
            return ; 
            
    }
  • 添加用戶信息展示的userList.jsp頁面:
<%@ page language="java" import="java.util.*,com.zlw.pojo.*" pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE html>
<html lang="zh-cn">
<head>
 <base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="renderer" content="webkit">
<title></title>
<link rel="stylesheet" href="css/pintuer.css">
<link rel="stylesheet" href="css/admin.css">
<script src="js/jquery.js"></script>
<script src="js/pintuer.js"></script>
</head>
<body>
<div class="panel admin-panel">
  <div class="panel-head"><strong class="icon-reorder"> 用戶信息列表</strong></div>
  <table class="table table-hover text-center">
    <tr>
      <th width="5%">ID</th>
      <th width="15%">用戶姓名</th>
      <th width="10%">密碼</th>
      <th width="10%">性別</th>
      <th width="10%">年齡</th>
      <th width="10%">出生日期</th>
      <th width="10%">操作</th>
    </tr>
        <c:forEach items="${lu}" var="u">
            <tr>
              <td width="5%">${u.uid}</td>
              <td width="15%">${u.uname}</td>
              <td width="10%">${u.pwd}</td>
              <td width="10%">${u.sex}</td>
              <td width="10%">${u.age}</td>
              <td width="10%">${u.birthday}</td>
             <td><div class="button-group"> <a class="button border-main" href="cateedit.html"><span class="icon-edit"></span> 修改</a> <a class="button border-red" href="data?method=delUserInfo&uid=${u.uid}" onclick="return del(1,2)"><span class="icon-trash-o"></span> 刪除</a> </div></td>
            </tr>
        </c:forEach>
  </table>
</div>
<script type="text/javascript">
function del(id,mid){
    if(confirm("您確定要刪除嗎?")){            
        
    }
}
</script>
</body>
</html>
新增界面

2.使用JSTL修改項目

  • 將傳統(tǒng)的jsp方式獲取全部替換為JSTL標簽:
  • login.jsp
<!-- 聲明jstl進行判斷 -->
                        <c:choose>
                            <c:when test="${sessionScope.flag=='loginFalse' }">
                            <div style="text-align: center;color:red;">用戶名或密碼錯誤</div>
                            </c:when>
                            <c:when test="${sessionScope.flag=='regSuccess' }">
                            <div style="text-align:center;color:red;">用戶注冊成功</div>
                            </c:when>
                        </c:choose>
                        <c:remove var="flag" scope="session"/>
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容