天天看點

8-JSP詳解3

一、HTTP 請求狀态碼

狀态碼 說明
200 正常通路
400 請求類型不比對
404 資源找不到
500 Java 程式抛異常

二、response 常用方法

response 就是響應的,作用就是響應用戶端請求。

  1. sendRedirect(String path) 重定向方法。
    • 建立兩個 jsp 檔案:forward.jsp 、target.jsp。從 forward 通路 target。
      response.sendRedirect("target.jsp")
                 
    • 重定向:response.sendRedicit(String path),建立一個請求的傳給下一個頁面。
    • 轉發:request.getRequestDispatcher(String path).forward(request, response),将請求傳給下一個頁面。
    • 重定向與轉發的差別:
      • 浏覽器通路 forward.jsp ,這是一次請求 forward.jsp 的請求,記成

        chrmoe->forward.jsp

        , 如果是轉發,那麼加上響應的應該是

        chrome->forward.jsp->target.jsp->chrmoe

        。位址欄不變
      • 如果是重定向,那麼在 forward.jsp 重新向到 target.jsp 這個過程中,

        chrmoe->forward.jsp

        這個請求會被殺死,重建生成一個

        chrome->target.jsp

        ,位址欄會改變
      • 如果說兩個頁面之間需要通過 request 來傳遞值,則必須使用轉發,不能使用重定向。如果使用者名和密碼正确,則跳轉到首頁(轉發),并且展示使用者名,否則重新回到登入頁面。(重定向)
    • 重定向與轉發小案例:建立

      login.jsp

      check.jsp

      weclome.jsp

      <%-- login.jsp --%>
      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <html>
      <head>
          <title>login</title>
      </head>
      <body>
      <form action="/check.jsp" method="post">
          使用者名: <input type="text" name="username" />
          密碼: <input type="password" name="password" />
          <input type="submit" value="登入">
      </form>
      </body>
      </html>
                 
      <%-- check.jsp --%>
      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <html>
      <head>
          <title>check</title>
      </head>
      <body>
      <%
          String username = request.getParameter("username");
          String password = request.getParameter("password");
          if (username.equals("admin") && password.equals("123456")){
              // 登入成功
              request.setAttribute("name", username);
              request.getRequestDispatcher("welcome.jsp").forward(request, response);
          }else {
              // 登入失敗
              response.sendRedirect("login.jsp");
          }
      %>
      </body>
      </html>
                 
      <%-- welcome.jsp --%>
      <%@ page contentType="text/html;charset=UTF-8" language="java" %>
      <html>
      <head>
          <title>Welcome</title>
      </head>
      <body>
      <%
          String username = (String) request.getAttribute("name");
      %>
      <%=username%>
      <h2>Welcome</h2>
      </body>
      </html>