1. 程式人生 > 實用技巧 >FastAPI連線mysql傻瓜式

FastAPI連線mysql傻瓜式

JSP

目錄

1. 什麼是JSP

Java Server Pages:Java 伺服器端頁面,也和Servlet一樣,用於動態web技術

最大的特點:

  • 寫JSP就像在寫HTML
  • 區別:
    • HTML只給使用者提供靜態的資料
    • JSP頁面中可以嵌入JAVA程式碼,為使用者提供動態資料

2. JSP原理

思路:JSP到底怎麼執行

  • 程式碼層面沒有任何問題

  • 伺服器內部工作

    • Tomcat中有一個work目錄

    • IDEA中使用Tomcat會在IDEA的Tomcat中產生一個work目錄

      C:\Users\Wang\AppData\Local\JetBrains\IntelliJIdea2020.2\tomcat\Unnamed_untitled\work

      我的電腦的地址:

      C:\Users\Wang\AppData\Local\JetBrains\IntelliJIdea2020.2\tomcat\Unnamed_Cookie-and-Session-Study\work\Catalina\localhost\ROOT\org\apache\jsp

      發現頁面轉變成了Java程式

  • 瀏覽器向伺服器傳送請求,不管訪問什麼資源,其實都是在訪問Servlet

  • JSP最終也會被轉換成為一個Java類

  • JSP本質上就是一個Servlet:繼承了HttpServlet

  • JSP原始碼分析

//初始化
public void _jspInit() {
}

//銷燬
public void _jspDestroy() {
}

//JSPService
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
    throws java.io.IOException, javax.servlet.ServletException {

  if (!javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) {
    final java.lang.String _jspx_method = request.getMethod();
    if ("OPTIONS".equals(_jspx_method)) {
      response.setHeader("Allow","GET, HEAD, POST, OPTIONS");
      return;
    }
    if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method)) {
      response.setHeader("Allow","GET, HEAD, POST, OPTIONS");
      response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSP 只允許 GET、POST 或 HEAD。Jasper 還允許 OPTIONS");
      return;
    }
  }
  1. 判斷請求(get還是post)

  2. 內建一些物件

    final javax.servlet.jsp.PageContext pageContext;	//頁面上下文
    javax.servlet.http.HttpSession session = null;		//Session
    final javax.servlet.ServletContext application;		//applicationContext
    final javax.servlet.ServletConfig config;			//config
    javax.servlet.jsp.JspWriter out = null;				//out
    final java.lang.Object page = this;					//page:當前
    
    HttpServletRequest request							//請求
    HttpServletResponse response						//響應
    
  3. 輸出頁面前增加的程式碼

    response.setContentType("text/html");				//設定頁面的相應型別
    pageContext = _jspxFactory.getPageContext(this, request, response,
    			null, true, 8192, true);
    _jspx_page_context = pageContext;
    application = pageContext.getServletContext();
    config = pageContext.getServletConfig();
    session = pageContext.getSession();
    out = pageContext.getOut();
    _jspx_out = out;
    

    以上的這些物件,我們可以在JSP頁面中直接使用

在JSP頁面中:

  • 只要是JAVA程式碼,就會原封不動的輸出

  • 如果是HTML程式碼,就會被轉換為:

    out.write("<html>\r\n");
    

    這樣的格式,輸出到前端

3. JSP基礎語法

任何語言都有自己的語法

JSP作為Java技術的一種應用,它擁有一些自己擴充的語法(瞭解,知道即可!)

Java所有語法都支援!

1. JSP表示式

  <%--JSP表示式
    作用:用來將程式的輸出,輸出到客戶端
    <%= 變數或表示式%>
  --%>
  <%=new java.util.Date()%>

2. JSP指令碼片段

<%--JSP指令碼片段--%>
<%
  int sum = 0;
  for (int i = 1; i <= 100; i++) {
    sum += i;
  }
  //可以直接用out.println輸出,裡面可以寫html程式碼
  out.println("<h1>Sum =" + sum + "</h1>");
%>

指令碼片段的再實現

<%
    int x = 10;
    out.println(x);
  %>
  <p>這是一個JSP文件</p>
  <%
    int y = 20;
    out.println(y);
  %>

  <hr>

  <%--在程式碼中嵌入HTML元素
      將花括號分開在兩個JSP片段中,這樣中間可以直接寫HTML程式碼
      同時,HTML程式碼中也可以巢狀JSP片段--%>
  <%
    for (int i = 0; i < 5; i++) {

  %>
    <h1>Hello, World! <%=i%></h1>
  <%
    }
  %>

3. JSP宣告

<%--JSP宣告
<%! 宣告%>
--%>
<%!
  static {
    System.out.println("loading Servlet!");
  }
  private int globalVar = 0;
  public void wang() {
    System.out.println("進入了方法wang()");
  }
%>

JSP宣告:會被編譯到JSP生成的Java類的類中!(作用域更高)

其他的(表示式,指令碼片段)就會被生成到_jspService方法中!

在JSP中嵌入Java程式碼即可

JSP的註釋不會在客戶端顯示,HTML的就會!

4. JSP指令

1. 定製錯誤頁面

<%@page errorPage="error/500.jsp" %>

1. 利用JSP

<%--
  Created by IntelliJ IDEA.
  User: Wang
  Date: 2020/8/19
  Time: 14:48
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<%--定製錯誤頁面--%>
<%--錯誤頁面走error資料夾下的500.jsp--%>
<%@page errorPage="error/500.jsp" %>
<head>
    <title>Title</title>
</head>
<body>

<%
    int x = 1 / 0;
%>

</body>
</html>

500.jsp

<%--
  Created by IntelliJ IDEA.
  User: Wang
  Date: 2020/8/19
  Time: 14:51
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%--顯示圖片--%>
<img src="../img/500.png" alt="500">

</body>
</html>

2. 利用web.xml跳轉

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--定製錯誤頁面跳轉的檔案-->
    <error-page>
        <error-code>404</error-code>
        <location>/error/404.jsp</location>
    </error-page>
    <error-page>
        <error-code>500</error-code>
        <location>/error/500.jsp</location>
    </error-page>

</web-app>

404.jsp

<%--
  Created by IntelliJ IDEA.
  User: Wang
  Date: 2020/8/19
  Time: 15:13
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<img src="../img/404.png" alt="404">

</body>
</html>

2. 使用公共資源

<%--
  Created by IntelliJ IDEA.
  User: Wang
  Date: 2020/8/19
  Time: 15:31
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

    <%--@include會將兩個頁面合二為一: 將多個jsp檔案合為一個,如果存在同名的物件會報錯--%>
    <%@include file="common/header.jsp"%>
        <h1>網頁主體</h1>
    <%@include file="common/footer.jsp"%>

    <hr>

    <%--JSP標籤
    jsp:include: 拼接頁面,本質還是三個,存在同名的物件會報錯
    --%>
    <jsp:include page="common/header.jsp"/>
        <h1>網頁主體</h1>
    <jsp:include page="common/footer.jsp"/>
</body>
</html>

footer.jsp

<%--
  Created by IntelliJ IDEA.
  User: Wang
  Date: 2020/8/19
  Time: 15:31
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<h1>我是footer</h1>

header.jsp

<%--
  Created by IntelliJ IDEA.
  User: Wang
  Date: 2020/8/19
  Time: 15:30
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<h1>我是Header</h1>

5. 九大內建物件

  • PageContext 存東西
  • Request 存東西
  • Response
  • Session 存東西
  • Application [ServletContext] 存東西
  • config [ServletConfig]
  • out
  • page 不用瞭解
  • exception

存東西的優先順序

pageContext.setAttribute("name1", "wamg_1");    //儲存的資料只在一個頁面中有效
request.setAttribute("name2", "wamg_2");        //儲存的資料只在一次請求中有效,請求轉發會攜帶這個資料
session.setAttribute("name3", "wamg_3");        //儲存的資料只在一次會話中有效,從開啟瀏覽器到關閉瀏覽器
application.setAttribute("name4", "wamg_4");    //儲存的資料只在伺服器中有效,從開啟伺服器到關閉伺服器

通過pageContext取出

<%--
  Created by IntelliJ IDEA.
  User: Wang
  Date: 2020/8/19
  Time: 16:08
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<%--內建物件--%>

<%
    pageContext.setAttribute("name1", "wamg_1");    //儲存的資料只在一個頁面中有效
    request.setAttribute("name2", "wamg_2");        //儲存的資料只在一次請求中有效,請求轉發會攜帶這個資料
    session.setAttribute("name3", "wamg_3");        //儲存的資料只在一次會話中有效,從開啟瀏覽器到關閉瀏覽器
    application.setAttribute("name4", "wamg_4");    //儲存的資料只在伺服器中有效,從開啟伺服器到關閉伺服器
%>

<%--指令碼片段中的程式碼會被原封不動的生成到XXX.jsp.java中--%>
<%--要求:這裡面的程式碼必須保證java語法的正確性--%>
<%
    //從pageContext取出,我們通過尋找的方式來
    //從底層到高層(作用域):page-->request-->session-->application
    //JVM:雙親委派機制
    String name1 = (String) pageContext.getAttribute("name1");
    String name2 = (String) pageContext.getAttribute("name2");
    String name3 = (String) pageContext.getAttribute("name3");
    String name4 = (String) pageContext.getAttribute("name4");
    String name5 = (String) pageContext.getAttribute("name5");  //不存在
%>

<%--使用EL表示式輸出
    ${}
    會過濾掉不存在的值
--%>
<h1>取出的值為:</h1>
<h3>${name1}</h3>
<h3>${name2}</h3>
<h3>${name3}</h3>
<h3>${name4}</h3>
<h3>${name5}</h3>

</body>
</html>

作用域對於物件的影響

注意,如果使用轉發,此時可以取到request的值!這是由於請求也被轉發了.但是page的值取不到了,因為不在同一個頁面上

<%--
  Created by IntelliJ IDEA.
  User: Wang
  Date: 2020/8/19
  Time: 16:41
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<%
    //從pageContext取出,我們通過尋找的方式來
    //從底層到高層(作用域)
    String name1 = (String) pageContext.getAttribute("name1");
    String name2 = (String) pageContext.getAttribute("name2");
    String name3 = (String) pageContext.getAttribute("name3");
    String name4 = (String) pageContext.getAttribute("name4");
    String name5 = (String) pageContext.getAttribute("name5");  //不存在
%>

<%--使用EL表示式輸出
    ${}
    會過濾掉不存在的值
--%>
<h1>取出的值為:</h1>
<h3>${name1}</h3>
<h3>${name2}</h3>
<h3>${name3}</h3>
<h3>${name4}</h3>
<h3>${name5}</h3>

<%--此時由於作用域的原因,只能取出name3和name4--%>

</body>
</html>

利用pageContext的scope屬性實行其他三個內建物件的存取

<%--
  Created by IntelliJ IDEA.
  User: Wang
  Date: 2020/8/19
  Time: 16:44
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<%--
    //scope: 作用域
    public void setAttribute(String name, Object attribute, int scope) {
        switch(scope) {
        case 1:
            this.mPage.put(name, attribute);
            break;
        case 2:
            this.mRequest.put(name, attribute);
            break;
        case 3:
            this.mSession.put(name, attribute);
            break;
        case 4:
            this.mApp.put(name, attribute);
            break;
        default:
            throw new IllegalArgumentException("Bad scope " + scope);
        }

    }
--%>

<%
    pageContext.setAttribute("hello1", "hello1", PageContext.SESSION_SCOPE);
    //等價於
    session.setAttribute("hello1", "hello1");
%>

</body>
</html>

利用pageContext實現轉發

<%--
  Created by IntelliJ IDEA.
  User: Wang
  Date: 2020/8/19
  Time: 17:03
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<%
    //以下是jsp中實現轉發的方式
    pageContext.forward("/index.jsp");
    //以下是Servlet中實現的轉發
    request.getRequestDispatcher("/index.jsp").forward(request, response);
%>

</body>
</html>

一些應用場景

request:客戶端向伺服器傳送請求,產生的資料,使用者看完就沒用了,比如:新聞.使用者看完沒用的!

session:客戶端向伺服器傳送請求,產生的資料,使用者用完一會還有用,比如:購物車

application:客戶端向伺服器傳送請求,產生的資料,一個使用者用完了,其他使用者還可能使用,比如:聊天資料

6. JSP標籤&JSTL標籤&EL表示式

1. EL表示式(Expression Language)

要匯入以下兩個包

<!--JSTL表示式的依賴-->
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl-api -->
<dependency>
    <groupId>javax.servlet.jsp.jstl</groupId>
    <artifactId>jstl-api</artifactId>
    <version>1.2</version>
</dependency>
<!--Standard標籤庫-->
<!-- https://mvnrepository.com/artifact/taglibs/standard -->
<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
</dependency>

EL表示式的格式:${}

  • 獲取資料
  • 執行運算
  • 獲取web開發的常用物件

2. JSP標籤

<%--
  Created by IntelliJ IDEA.
  User: Wang
  Date: 2020/8/19
  Time: 17:28
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h1>1</h1>

<%--<jsp:include page=""/>--%>

<%--攜帶引數的訪問,url如下--%>
<%--http://localhost:8080/jsptag.jsp?value1=value1&value2=value2--%>
<jsp:forward page="jsptag2.jsp">
    <jsp:param name="value1" value="value1"/>
    <jsp:param name="value2" value="value2"/>
</jsp:forward>

</body>
</html>

在jsptag2.jsp中取出引數,用JSP的request物件

<%--
  Created by IntelliJ IDEA.
  User: Wang
  Date: 2020/8/19
  Time: 17:30
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h1>2</h1>

<%--取出引數--%>
<p>值1:<%=request.getParameter("value1")%></p>
<p>值2:<%=request.getParameter("value2")%></p>

</body>
</html>

3. JSTL表示式

JSTL標籤庫的使用就是為了彌補HTML標籤的不足;它自定義了許多標籤,可以供我們使用,標籤的功能和Java程式碼一樣

1. 核心標籤(掌握部分)

JSTL 核心標籤庫標籤共有13個,功能上分為4類:

1.表示式控制標籤:out、set、remove、catch

2.流程控制標籤:if、choose、when、otherwise

3.迴圈標籤:forEach、forTokens

4.URL操作標籤:import、url、redirect

2. 使用步驟

  • 引用對應的taglib
  • 使用其中的方法
  • 在tomcat中也需要引入JSTL的包(jstl和standard的jar包),否則會報錯JSTL解析錯誤的包

3. 測試程式碼

if

<%--
  Created by IntelliJ IDEA.
  User: Wang
  Date: 2020/8/20
  Time: 9:43
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--引入JSTL核心標籤庫,我們才能使用JSTL標籤--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<h4>if測試</h4>

<form action="coreif.jsp" method="get">
    <%--
    EL表示式獲取表單中的資料
    ${param.引數名}
    --%>
    <input type="text" name="username" value="${param.username}">
        <input type="submit" value="登陸">
</form>

<%--判斷如果提交的使用者名稱是管理員,則提交成功--%>
<c:if test="${param.username == 'admin'}" var="isAdmin">
    <c:out value="管理員歡迎您!"/>
</c:if>

<%--自閉合標籤--%>
<c:out value="${isAdmin}"/>

</body>
</html>

switch

<%--
  Created by IntelliJ IDEA.
  User: Wang
  Date: 2020/8/20
  Time: 10:12
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--引入JSTL核心標籤庫,我們才能使用JSTL標籤--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<%--定義一個變數score,值為85--%>
<c:set var="score" value="85"/>

<%--c:chose相當於switch--%>
<%--c:when是條件--%>
<c:choose>
    <c:when test="${score >= 90}">
        你的成績為優秀
    </c:when>
    <c:when test="${score >= 80}">
        你的成績為一般
    </c:when>
    <c:when test="${score >= 70}">
        你的成績為良好
    </c:when>
    <c:when test="${score >= 60}">
        你的成績為及格
    </c:when>
</c:choose>

</body>
</html>

foreach

<%@ page import="java.util.ArrayList" %>
<%--
  Created by IntelliJ IDEA.
  User: Wang
  Date: 2020/8/20
  Time: 10:17
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--引入JSTL核心標籤庫,我們才能使用JSTL標籤--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

<%
    ArrayList<String> people = new ArrayList<>();
    people.add("張三");
    people.add("李四");
    people.add("王五");
    people.add("趙六");
    people.add("錢七");
    request.setAttribute("list", people);
%>

<%--var,每一次遍歷出來的變數--%>
<%--items,要遍歷的物件--%>
<c:forEach var="people" items="${list}">
    <c:out value="${people}"/>
    <br>
</c:forEach>
<%--
var     每一次遍歷出來的變數
items   要遍歷的物件
begin   從哪裡開始(索引從0開始)
end     到哪裡
step    步長
--%>
<c:forEach begin="1" end="3" step="2" var="people" items="${list}">
    <c:out value="${people}"/>
    <br>
</c:forEach>

</body>
</html>