1. 程式人生 > >Java EE Web部分--05.JSP、EL、JSTL

Java EE Web部分--05.JSP、EL、JSTL

學習目標

JSP (Java Server Pages)

EL ( Expression Language )

JSTL (The JavaServer Pages Standard Tag Library)

一、JSP

1、概述

JSP全名為Java Server Pages 、java伺服器頁面。既能寫html程式碼、又能寫Servlet、其本質是一個簡化的Servlet。

建立:如圖idea

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

</body>
</html>

2、jsp原理

當我們通過瀏覽器訪問到jsp頁面、最終訪問的是tomcat伺服器中的jsp頁面。下面我們可以通idea釋出web專案。

當啟動tomcat時可看到下面的資訊

 C:\Users\root\.IntelliJIdea2018.2\system\tomcat\Tomcat_8_5_31_day10Ajax\work\Catalina\localhost\ROOT\org\apache\jsp

 

  開啟index_jsp.java檔案後,發現我們在JSP頁面上寫的程式碼都在_jspService方法中:

1. <% %> 中書寫的程式碼被直接解析成java程式碼;
2. html部分都被out.write("")方法以字串的形式拼接,然後響應給瀏覽器;
3. 在這個java檔案中有個_jspService,這個方法有兩個引數request,response。
   由此可看出JSP本質上就是一個Servlet。

3、jsp中書寫java程式碼三種方式

jsp頁面中書定java程式碼要使用三種方法:

3.1、指令碼片段<% java程式碼 %>

指令碼片段指的是一段java程式碼 demo2.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%--
    response.getWriter().println()任意資料
    response.getWriter().write//只能輸出字元  字元陣列 字串
--%>
<%
    response.getWriter().println("hello jsp");
    response.getWriter().write(65);
%>
</body>
</html>

response.getWriter().write(65);輸出的是A。A的ASCII是65。

3.2、指令碼宣告<%! java程式碼 %>

宣告成員方法和屬性  demo3.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%--
成員變數 int num = 0;
 public void method(){}
--%>
<%!
    int num = 10;
    public void method(){}
%>
</body>
</html>

【被翻譯後的程式碼】成員變數

3.3、指令碼表示式<%=內容%>

指令碼表示式的格式:<%= 內容 %> 等價於:out.print(內容)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
    out.println("hello out");
    response.getWriter().println("response");
%>
<%="我愛JAVA"%>
</body>
</html>
【小結】

1. 指令碼表示式<%= str %> :在頁面輸出內容,
2. 指令碼片段<%  %> :在service方法中,原樣輸出的程式碼片段;
3. 指令碼宣告:<%! String str = "我愛java" %> :定義成員變數;
write() 和println()區別

(1)、write():僅支援輸出字元型別資料,字元、字元陣列、字串等

(2)、print():可以將各種型別(包括Object)的資料通過預設編碼轉換成bytes位元組形式,這些位元組
response.getWriter().println();先輸出、out.write(65)後輸出

4、登入案例

登入程式碼:

@WebServlet("/loginServletin")
public class LoginInServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解決中文亂碼問題
        request.setCharacterEncoding("utf-8");
        //獲取使用者名稱和密碼
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //使用service層來解決業務邏輯
        UserServiceIn serviceIn = new UserServiceInImpl();
        boolean result = serviceIn.login(username,password);

        if (result){
            //登陸成功  需要攜帶資料
            //使用 重定向
//            request.getRequestDispatcher("/success.html").forward(request,response);
            response.sendRedirect("/success.html");
        }else {
            //登陸失敗  應用去login.html
            //希望使用者得到 登陸錯誤資訊


            //使用轉發  servlet處理業務太多了,程式碼臃腫問題
            request.setAttribute("msg","使用者名稱或者密碼錯誤");
            request.getRequestDispatcher("/login.jsp").forward(request,response);

        }

    }
}

login.jsp登入頁

<body>
<%
//    String str = (String) request.getAttribute("msg");
%>
<div class="container text-center">
    <form class="form-signin" action="/loginServletin" method="post">
        <font color="red"><%=str%></font>   
        <h2 class="form-signin-heading">登入頁面</h2>
        <input type="text"  name="username" class="form-control" placeholder="使用者名稱" required autofocus>
        <input type="password"  name="password" class="form-control" placeholder="密碼" required>
        <button class="btn btn-lg btn-primary btn-block" type="submit">登入</button>
    </form>
</div>

</body>

當登入出錯時會顯示如下 

 

二、EL表示式

1、概述

EL全稱: Expression Language 

作用:代替jsp中指令碼表示式的功能,簡化對java程式碼的操作,從【域物件】中取值。 EL表示式簡化<%= %>方式取值   
EL語法表示式的格式:${表示式內容} 

2、EL取值

2.1、JSP的四大域物件

JSP的四大域物件指的是:page域,request域,session域,application域。我們通常使用EL表示式從這4個域物件用取值。以下是這4個域物件的詳細資訊:

域物件 物件名稱 說明
page域 pageScope page域指的是當前JSP頁面,其中儲存的資料只在當前頁面有效
request域 requestScope request域:一次請求或請求鏈中request域
session域 sessionScope session域:一次會話過程中,session域
application域 applicationScope application域:服務啟動後整個專案對應的ServletContext域

2.2、EL表示式從四大域中取值

​ EL表示式從指定的域中取值的方式如下:

域物件 取值方式
page域 ${pageScope.xxx}
request域 ${requestScope.xxx}
session域 ${sessionScope.xxx}
application域 ${applicationScope.xxx}

程式碼:

<body>
<%--
EL表示式 page  request  session  application 四大域物件
--%>
<%
    pageContext.setAttribute("pageValue","page的值");
    request.setAttribute("requestValue","request的值");
    request.getSession().setAttribute("sessionValue","session的值");
    application.setAttribute("applicationValue","applicatin的值");
%>
<%--
EL表示式來域物件中取值
--%>
page中取值:${pageScope.pageValue}<br>
request中取值:${requestScope.requestValue}<br>
session中取值${sessionScope.sessionValue}<br>
application中取值${applicationScope.applicationValue}<br>
</body>

2.3、EL表示式搜尋資料

EL表示式取值的時候也可以不指定域,如果取值的時候不指定域物件。就會按照從page域--->request域--->session域--->servletContext域從小到大逐級根據name屬性值查詢。

<body>
<%
    pageContext.setAttribute("pageValue","page的值");
    request.setAttribute("requestValue","request的值");
    request.getSession().setAttribute("sessionValue","session的值");
    application.setAttribute("applicationValue","applicatin的值");

    pageContext.setAttribute("value","page的值");
    request.setAttribute("value","requst的值");
%>
<%--
預設從最小的域物件的範圍-->最大域物件。
--%>
page中取值:${pageScope.pageValue}<br>
page:${pageValue}<br>
request中取值:${requestValue}<br>
session中取值${sessionValue}<br>
application中取值${applicationValue}<br>

相同key:${value}
</body>

2.4、EL表示式cookie中取值

語法格式:${cookie.cookie名稱.value} 取出單個cookie的值

java程式碼:CreateCookieServlet.java

@WebServlet("/create")
public class CreateCookieServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //建立cookie
        Cookie cookieName = new Cookie("name","lisi");
        Cookie cookiePsw = new Cookie("password","1234");

        response.addCookie(cookieName);
        response.addCookie(cookiePsw);
    }
}

demo7.jsp

<body>
<form action="" method="post">
    使用者名稱:<input type="text" name="username" value="${cookie.name.value}"><br>
    密碼:<input type="text" name="password" value="${cookie.password.value}"><br>
    <input type="submit" value="提交">
</form>
</body>

再訪問demo07.jsp頁面,使用EL表示式獲取使用者名稱和密碼

3、EL運算子

3.1 算術運算

​ 顧名思義,算術運算是進行算術運算的符號,主要包括:加,減,乘,除。具體使用如下表:

運算子 說明 使用示例 結果
+ ${n1+n2} 30
- ${n1-n2} -10
* ${n1*n2} 200
/或div ${n1/n2}
%或mod 取餘

3.2 關係運算

關係運算符是判斷兩個資料的大小關係的,關係運算符有:==,!=,<,<=,>,>=。具體使用方法如下:

運算子 說明 使用示例 結果
== 或 eq 等於 equal ${n1 == n2} false
!= 或ne 不等於 not equal ${n1 != n2} true
> 或 gt 大於 greater than ${n1 > n2} false
>= 或ge 大於等於 greater than or equal ${n1 >= n2} false
< 或 lt 小於 less than ${n1 < n2} true
<= 或le 小於等於 less than or equal ${n1 <= n2} true

3.3 邏輯運算

邏輯運算子包括:&& ,||,!使用方法如下:

運算子 說明 使用示例 結果
&& 或 and 邏輯與 ${true && false} false
|| 或 or 邏輯或 `${true
! 或 not ${!false} true

3.4 三元運算

<%--
 表示式1?表示式2:表示式3
--%>
三元運算子:<br>
${n1>=n2?"正確":"錯誤!"}<br>

3.5 empty運算

empyt運算子對以下資料運算返回true:

1. 字串:"";
2. 空集合(size=0):List  list = new ArrayList();
3. 空物件(null):Student stu = null;

小結:

EL表示式小結:

  • EL:Expression Language;

  • EL語法:${ }

  • 作用:簡化指令碼表示式的取值,簡化<%= request.getAttribute("name") %> ===> ${name}

  • jsp的四大域物件

    • page域:pageContext pageContext.setAttrubute() pageContext.getAttribute() JSP特有 作用範圍:當前的JSP頁面

    • requst域:request request.setAttribute() request.getAttribute() 作用範圍:一次請求和響應之間

    • session域: session session.setAttribute() session.getAttribute() 作用範圍:會話期間(多次請求和響應)

    • servletContext域:application application.setAttribute() application.getAttribute() 作用範圍:整個專案;

  • jsp從四大域中取值(指定域物件):

    • ${pageScope.name}

    • ${requestScope.name}

    • ${sessionScope.name}

    • ${applicationScope.name}

  • JSP搜尋域物件中的值:page --- request --- session --- servletContext

    • ${name}

  • 運算

    • 算術運算

    • 關係運算

    • 邏輯運算:&& || !

    • 三元運算

    • empty運算:empty not  empty

      • 空字串:""

      • 空物件:null

      • 空集合:list.size = 0;

三、JSTL標籤庫

1、概述

Apache Jakarta小組開發了一套用於解決這些常用問題的自定義標籤庫, 這套標籤庫被SUN公司定義為標準標籤庫(The JavaServer Pages Standard Tag Library),簡稱JSTL。

2、安裝使用JSTL

JSTL標籤是將一段java程式碼功能封裝成一個標籤來使用。所以,我們使用JSTL標籤之前必須匯入被封裝的java程式碼---jar包。JSTL標籤庫主要依賴以下兩個jar包:

在JSP頁面中通過以下標籤,通過taglib標籤引入JSTL資源:

 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
注意】

1. prefix:是jstl標籤在使用的時候的字首;
2. uri:是標籤庫的資源路徑;

3、常用JSTL標籤

JSTL核心標籤庫

標籤名稱 作用
<c:out> 通常用於輸出一段文字內容到客戶端瀏覽器
<c:set> 用於設定各種Web域中的屬性
<c:remove> 用於刪除各種Web域中的屬性
<c:catch> 用於捕獲巢狀在標籤體中的內容丟擲的異常
<c:if> 使用者java程式碼if(){}語句功能
<c:choose> 用於指定多個條件選擇的組合邊界,它必須與c:when和c:otherwise標籤一起使用
<c:forEach> 使用者代替java程式碼for迴圈語句
<c:forTokens> 使用者迭代操作String字元
<c:param> 給請求路徑新增引數
<c:url> 重寫url,在請求路徑新增sessionid
<c:import> 用於在JSP頁面中匯入一個URL地址指向的資源內容
<c:redirect> 用於將當前的訪問請求轉發或重定向到其他資源

 <c:if>格式:

<c:if test=條件判斷 >標籤的作用相當於java中的if判斷語句。

if(條件判斷){}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
    session.setAttribute("user","username");
%>
<c:if test="${user==null}">
    <c:out value="請登入"></c:out>
</c:if>
<c:if test="${user!= null}">
    <c:out value="登入成功"></c:out>
</c:if>
</body>
</html>

<c:foreach>遍歷

屬性如下:

var:在不迴圈物件的時候,儲存的是控制迴圈的變數;在迴圈物件的時候,儲存的是被迴圈物件中的元素
items:指定要迴圈的物件
varStatus:儲存了當前迴圈過程中的資訊(迴圈的開始、結束、步長、次數等)
begin:設定迴圈的開始
end:設定迴圈的結束
step:設定步長——間隔幾次迴圈,執行一次迴圈體中的內容

演示一:list遍歷

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%--
使用EL表示式和JSTL將資料遍歷出來,填放在標籤裡面
--%>

<c:forEach items="${list}" var="product">
    驚爆價:<font color="red">${product.price}</font>商品名稱:<font color="aqua">${product.name}</font><br>
</c:forEach>
</body>
</html>

ProductServlet.java

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/produceServlet")
public class ProduceServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //去資料庫查詢商品資訊
        Product product1 = new Product(9.9,"布娃娃");
        Product product2 = new Product(99,"蘋果");
        Product product3 = new Product(12000,"電腦");
        Product product4 = new Product(8,"滑鼠");
        Product product5 = new Product(20,"杯子");

        List<Product> list = new ArrayList<>();
        list.add(product1);
        list.add(product2);
        list.add(product3);
        list.add(product4);
        list.add(product5);

        //將資料儲存在域物件中
        request.setAttribute("list",list);
        //使用轉發  list.jsp

        request.getRequestDispatcher("/list.jsp").forward(request,response);

    }
}

實體類Product

public class Product {
    private int id;
    private double price;
    private String name;

    public Product(double price, String name) {
        this.price = price;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", price=" + price +
                ", name='" + name + '\'' +
                '}';
    }
}

演示二:map集合

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
    Map map = new HashMap();
    map.put("one","郭德綱");
    map.put("two","c羅");
    map.put("thr","小羅");
    map.put("four","賈寶玉");
    request.setAttribute("map",map);
%>

<c:forEach items="${map}" var="item">
    明星人物key:${item.key}+value:${item.value}<br>
</c:forEach>
</body>
</html>

choose標籤作用

<c:choose>標籤用於指定多個條件選擇的組合邊界,它必須與<c:when>和<c:otherwise>標籤一起使用。

演示:choose.jsp

<body>
<c:choose>
    <c:when test="${temp == 1}">
        <c:out value="一年級"></c:out>
    </c:when>
    <c:when test="${temp == 2}">
        <c:out value="二年級"></c:out>
    </c:when>
    <c:when test="${temp == 3}">
        <c:out value="三年級"></c:out>
    </c:when>
    <c:when test="${temp == 4}">
        <c:out value="四年級"></c:out>
    </c:when>
    <c:when test="${temp == 5}">
        <c:out value="五年級"></c:out>
    </c:when>
    <c:otherwise>
        <c:out value="輸入有誤"></c:out>
    </c:otherwise>
</c:choose>
</body>

switchServlet.java

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/switchServlet")
public class SwitchServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //實現switch功能
        int temp = 7;
      
        //轉發到servlet
        request.setAttribute("temp",temp);
        //轉發到choose.jsp

        request.getRequestDispatcher("/choose.jsp").forward(request,response);
    }
}