JavaWeb_請求轉發


請求的轉發和重定向:

 

1)本質區別:請求的轉發只發出一次請求,而重定向則發出來兩次請求。

具體:

①請求的轉發:地址欄是初次發出請求的地址

    請求的重定向:地址欄不再是初次發出的請求地址,地址欄為最后響應的那個地址

②請求轉發:在最終的Servlet中,request對象和中轉的那個request是同一個對象

    請求的重定向:在最終的Servlet中,request對象和中轉的那個request不是同一個對象

(3)請求的轉發:只能轉發給當前WEB應用的資源

  請求的重定向:可以重定向到任何資源。

④請求轉發:/ 代表的是當前WEB應用的根目錄

 請求重定向:/ 代表的是當前WEB站點的根目錄

 

JSP

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<a href="ForwardServlet">ForwardServlet</a>

<br>

<a href="RedirectServlet">RedirectServlet</a>
</body>
</html>

  

Servlet

public class ForwardServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }




    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("ForwardServlet's doGet");

        /**
         * 請求的轉發
         * 1.調用HttpServletRequest的getRequestDispatcher()方法獲取RequestDispatcher對象
         * 調用getRequestDispatcher()需要傳入要轉發的地址
         */
        String path = "/TestServlet";

        RequestDispatcher requestDispatcher = request.getRequestDispatcher(path);
         /**
         * 2.調用HttpServletRequest的forward(request,response)進行請求的轉發
         */
         requestDispatcher.forward(request,response);

    }
public class TestServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("TestServlet's doGet");
    }
}


@WebServlet(name = "RedirectServlet")
public class RedirectServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("RedirectServlet's doGet");
        //執行請求的重定向,直接調用response,sendRedirect(path)方法
        //path為要重定向的地址
        String path = "TestServlet";
        response.sendRedirect(path);
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM