一、前言
其實javaweb案例前兩個只不過是給我們練練手,復習復習基礎用的。沒有掌握也沒有關系,然而重定向才是最重要的技術,我們需要重點掌握重定向技術。
二、實現重定向
一個web資源收到客戶端請求后,他會通知客戶端去訪問另外一個web資源,這個過程就是重定向。
常見場景:
- 用戶登錄
void sendRedirect(String var1) throws IOException;
- 1
代碼測試:
@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /* resp.setHeader("Location","/r/img"); resp.setStatus(302); */ resp.sendRedirect("/r/img"); //重定向 }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
結果在瀏覽器中訪問效果如下:路徑從 /red 自動跳轉到 /img

三、面試題:重定向和請求轉發的區別
相同點:
- 頁面都會實現跳轉
不同點:
- 請求轉發時候,url不會產生變化
- 重定向時候,url地址欄會發生變化
四、使用重定向技術做一個小Demo
最開始我們要做好准備工作:
先創建一個Maven項目,導入jsp依賴,代碼如下:
<dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> </dependency>
- 1
- 2
- 3
- 4
- 5
步驟:
- 創建一個類繼承HttpServlet類,重寫doGet()和doPost()。該類的url-pattern(訪問路徑)為是 /login :
package com.xu.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class RequestTest extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //處理請求 String username = req.getParameter("username"); String password = req.getParameter("password"); System.out.println(username + ":" + password); //重定向的時候,一定要注意路徑問題,否則就會404 resp.sendRedirect("/r/success.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 根據代碼我們可以看出,我們重定向的資源路徑為/success.jsp。該jsp頁面的代碼如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html> <head> <title>Title</title> </head> <body> <h1>Success</h1> </body> </html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 我們在index.jsp(開啟服務器后,首次訪問的頁面)頁面中添加form表單,作為登錄頁面,效果如下:
代碼如下:
<html> <body> <h2>Hello World!</h2> <%--這里提交的路徑,需要尋找到項目的路徑--%> <%--${pageContext.request.contextPath}代表當前項目--%> <form action="${pageContext.request.contextPath}/login" method="get"> 用戶名:<input type="text" name="username"> <br> 密碼:<input type="password" name="password"> <br> <input type="submit"> </form> </body> </html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
最后我們打開服務器,首先會彈出登錄頁面,提交表單后,會訪問RequestTest類資源,由於該類中代碼使用重定向技術會將頁面定向到success.jsp頁面,以上就是重定向技術的展示。
