015_请求转发和重定向
一. 重定向和轉(zhuǎn)發(fā)工程
1. 新建一個(gè)SendRedirectForward的Web工程
2. 在WebContent下新建index.html和success.html
3. 編寫index.html
<!DOCTYPE html> <html><head><meta charset="UTF-8" /><title>重定向和轉(zhuǎn)發(fā)</title></head><body><a href="SendRedirect.action">重定向</a><br/><a href="Forward.action">轉(zhuǎn)發(fā)</a></body> </html>4. 編寫success.html
<!DOCTYPE html> <html><head><meta charset="UTF-8" /><title>success</title></head><body><h1>success</h1></body> </html>5. 新建SendRedirect.java和Forward.java
6. 編寫SendRedirect.java
package com.lywgames.myservlet;import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;public class SendRedirect extends HttpServlet {private static final long serialVersionUID = 1L;@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {resp.sendRedirect("success.html");}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} }7. 編寫Forward.java
package com.lywgames.myservlet;import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;public class Forward extends HttpServlet {private static final long serialVersionUID = 1L;@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {req.getRequestDispatcher("success.html").forward(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} }8. 編寫web.xml
9. 部署運(yùn)行
10. 打開chrome的開發(fā)者選項(xiàng), 點(diǎn)擊重定向
11. 打開chrome的開發(fā)者選項(xiàng), 點(diǎn)擊轉(zhuǎn)發(fā)
二. 重定向和轉(zhuǎn)發(fā)
1. 重定向
1.1.?重定向?qū)懛? 使用HttpServletResponse的sendRedirect方法, 參數(shù)是重定向的位, 即跳轉(zhuǎn)的位置。response.sendRedirect("success.html")。
1.2.?地址欄上顯示的是最后的那個(gè)資源的路徑地址。
1.3.?請(qǐng)求次數(shù)最少有兩次, 服務(wù)器在第一次請(qǐng)求后, 會(huì)返回302和一個(gè)地址,?瀏覽器在根據(jù)這個(gè)地址, 執(zhí)行第二次訪問。
1.4.?可以跳轉(zhuǎn)到任意路徑, 不是自己的工程也可以跳。
1.5.?效率稍微低一點(diǎn), 執(zhí)行兩次請(qǐng)求。
1.6.?后續(xù)的請(qǐng)求, 沒法使用上一次的request存儲(chǔ)的數(shù)據(jù), 或者沒法使用上一次的request對(duì)象, 因?yàn)檫@是兩次不同的請(qǐng)求。
2. 轉(zhuǎn)發(fā)
2.1.?請(qǐng)求轉(zhuǎn)發(fā)的寫法, 參數(shù)即跳轉(zhuǎn)的位置: request.getRequestDispatcher("success.html").forward(request, response);
2.2.?地址欄上顯示的是請(qǐng)求servlet的地址, 返回200(ok)。
2.3.?請(qǐng)求次數(shù)只有一次, 因?yàn)槭欠?wù)器內(nèi)部幫客戶端執(zhí)行了后續(xù)的工作。
2.4.?只能跳轉(zhuǎn)自己項(xiàng)目的資源路徑 。 ?
2.5.?效率上稍微高一點(diǎn), 因?yàn)橹粓?zhí)行一次請(qǐng)求。
2.6.?可以使用上一次的request對(duì)象。
總結(jié)
以上是生活随笔為你收集整理的015_请求转发和重定向的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 012_HttpServletRespo
- 下一篇: 016_Servlet上下文