重定向
1.概述
瀏覽器請求服務器,服務器通過HTTP協議約定響應頭去告訴瀏覽器,並實現請求
狀態碼:302
2.特點
a.兩次請求,兩次響應
b.地址欄會發生變化
c.可以跳轉到外部站點資源,也可以跳轉到內部站點的資源
3.方法
a.方式1
response.setStatus(302);設置狀態碼
response.setHeader("location", "網址");設置頭,跳轉外部網址
b.方式2response.setHeader("location", "內部文件");設置頭,跳轉內部資源
response.sendRedirect("跳轉地址");
String method = request.getMethod();
// 獲取URI
String uri = request.getRequestURI();
// 獲取URL StringBuffer url = request.getRequestURL();
// 獲取協議版本
String protocol = request.getProtocol();
// 獲取ip
String ip = request.getRemoteAddr();
// 獲取主機名
String host = request.getRemoteHost();
// 獲取端口
int port = request.getRemotePort();
System.out.println(method);
System.out.println(uri);
System.out.println(url);
System.out.println(protocol);
System.out.println(ip);
System.out.println(host);
System.out.println(port);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
處理請求:解決中文亂碼
處理表單提交後臺的數據
a.處理get請求
get請求參數拼接在URL後面,通過getQueryString();獲取請求參數
獲取的是瀏覽器進行了一個URLEncode()編碼後的值
要通過URLDecoder.decode();進行編碼,否則會出現中文亂碼
b.處理post請求
post請求把請求參數封裝在請求體裏面
通過request.getReader().readLine();獲取
然後通過decode進行編碼
c.驗證
在index.jsp中寫一個表單,提交用戶名(中文)和密碼
觀察控制檯獲取的參數
String line = request.getQueryString();
// 通過decode進行編碼 username=張三&password=123456
line = URLDecoder.decode(line, "utf-8");
// 獲取信息
// 截取&
String[] split = line.split("&");
// 截取=獲取信息
String username = split[0].split("=")[1];
String password = split[1].split("=")[1];
System.out.println(username + "---" + password);
}
// post請求
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 從請求體中獲取處參數
String line = request.getReader().readLine();
// 轉碼 username=張三&password=123456
line = URLDecoder.decode(line, "utf-8");
// 獲取信息
// 截取&
String[] split = line.split("&");
// 截取=獲取信息
String username = split[0].split("=")[1];
String password = split[1].split("=")[1];
System.out.println(username + "---" + password);
}
請求域
1.request
a.是一個請求對象,用來封裝請求消息
b.是一個域對象,可以在他的範圍內共享數據
c.請求的範圍:一次請求和一次響應之間
2.請求轉發
a.request.getRequestDispatcher("/mydemo").forward(request, response);
將當前請求轉向1mydemo2,不用輸入工程名
b.特點
1)一次請求一次響應
2)地址欄不發生變化
3)只能訪問內部站點資源
c.什麼時候使用重定向?什麼時候使用轉發?
1)如果需要在請求的多個資源中共享數據,則使用轉發
2)如一次性的數據存入請求域中