一、前言
其實javaweb案例前兩個只不過是給我們練練手,復習復習基礎用的,沒有掌握也沒有關系,然而重定向才是最重要的技術,我們需要重點掌握重定向技術,
二、實作重定向
一個web資源收到客戶端請求后,他會通知客戶端去訪問另外一個web資源,這個程序就是重定向,
常見場景:
- 用戶登錄
void sendRedirect(String var1) throws IOException;
代碼測驗:
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
/*
resp.setHeader("Location","/r/img");
resp.setStatus(302);
*/
resp.sendRedirect("/r/img"); //重定向
}
結果在瀏覽器中訪問效果如下:路徑從 /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>
步驟:
- 創建一個類繼承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);
}
}
- 根據代碼我們可以看出,我們重定向的資源路徑為/success.jsp,該jsp頁面的代碼如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>Success</h1>
</body>
</html>
- 我們在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>
最后我們打開服務器,首先會彈出登錄頁面,提交表單后,會訪問RequestTest類資源,由于該類中代碼使用重定向技識訓將頁面定向到success.jsp頁面,以上就是重定向技術的展示,

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/200683.html
標籤:java
上一篇:CSS的字體樣式
下一篇:gin使用自定義結構系結表單資料
