jsp跳轉getRequestDispatcher()和sendRedirect()的區別_JSP編程

來源:互聯網
上載者:User

1.request.getRequestDispatcher()是請求轉寄,前後頁面共用一個request ;
response.sendRedirect()是重新定向,前後頁面不是一個request。

2.RequestDispatcher.forward()是在伺服器端運行;
HttpServletResponse.sendRedirect()是通過向客戶瀏覽器發送命令來完成.
所以RequestDispatcher.forward()對於瀏覽器來說是“透明的”;
而HttpServletResponse.sendRedirect()則不是。

3.ServletContext.getRequestDispatcher(String url)中的url只能使用絕對路徑; 而ServletRequest.getRequestDispatcher(String url)中的url可以使用相對路徑。因為ServletRequest具有相對路徑的概念;而ServletContext對象無次概念。

RequestDispatcher對象從用戶端擷取請求request,並把它們傳遞給伺服器上的servlet,html或jsp。它有兩個方法:

1.void forward(ServletRequest request,ServletResponse response)

用來傳遞request的,可以一個Servlet接收request請求,另一個Servlet用這個request請 求來產生response。request傳遞的請求,response是用戶端返回的資訊。forward要在response到達用戶端之前調用,也 就是 before response body output has been flushed。如果不是的話,它會報出異常。

2.void include(ServletRequest request,ServletResponse response)

用來記錄保留request和response,以後不能再修改response裡表示狀態的資訊。

如果需要把請求轉移到另外一個Web App中的某個地址,可以按下面的做法:
1. 獲得另外一個Web App的ServletConext對象(currentServletContext.getContext(uripath)).

2. 調用ServletContext.getRequestDispatcher(String url)方法。

eg:ServletContext.getRequestDispatcher(“smserror.jsp”).forward(request,response);

代碼執行個體:
index.jsp:

複製代碼 代碼如下:

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>

My JSP 'index.jsp' starting page
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3" />
<meta http-equiv="description" content="This is my page" />
    <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
    -->
<form action="servlet/session" method="post">
  使用者名稱:<input type="text" name="username" />

  密碼:<input type="password" name="password" />

  <input type="submit" />
  </form>

session.java:

複製代碼 代碼如下:

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class session extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public session() {
        super();
    }

    /**
     * Destruction of the servlet.

     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet.

     *
     * This method is called when a form has its tag value method equals to get.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    /**
     * The doPost method of the servlet.

     *
     * This method is called when a form has its tag value method equals to post.
     *
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = "";
        String password = "";
        username = request.getParameter("username");
        password = request.getParameter("password");
        HttpSession session = request.getSession();
        session.setAttribute("username", username);
        session.setAttribute("password", password);
        request.setAttribute("name", username);
        request.setAttribute("pwd", password);

        RequestDispatcher dis = request.getRequestDispatcher("/getsession.jsp");
        dis.forward(request, response);

        /*
        response.sendRedirect("http://localhost:8080/sessiontest/getsession.jsp");
        */
                //這個路徑必須是這樣寫,而不能像上面的request.getRequestDispatcher那樣使用相對路徑
                //  而且要是使用response.sendRedirect的話在下面的session.jsp中不能通過request.getAttribute來擷取request對象
                //因為前後使用的不是同一個request,但是session可以,因為session會一直存在直到使用者關閉瀏覽器
    }

    /**
     * Initialization of the servlet.

     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

getsession.jsp:

複製代碼 代碼如下:

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>

My JSP 'getsession.jsp' starting page

<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3" />
<meta http-equiv="description" content="This is my page" />
    <!--
        <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  <%   out.print("");   String username = (String)session.getAttribute("username");  
String password = (String)session.getAttribute("password");  
String name = (String)request.getAttribute("name");  
String pwd = (String)request.getAttribute("pwd"); 
 out.println("username " + username + " password " +password);
 //如果上面是使用response.sendRedirect的話就不能擷取到name和pwd  
 out.println("name " + name + "pwd "+ pwd);   
  %>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.