请求转发与请求重定向的区别

来源:互联网 发布:mac制作win7安装u盘 编辑:程序博客网 时间:2024/06/06 00:25

请求转发与请求重定向的区别
请求转发:

请求转发,即request.getRequestDispatcher().forward(),是一种服务器的行为,客户端只有一次请求,服务器端转发后会将请求对象保存,地址栏中的URL地址不会改变,得到响应后服务器端再将响应发给客户端;

请求重定向:

请求重定向,即response.sendRedirect(),是一种客户端行文,从本质上讲等同于两次请求,前一次请求对象不会保存,地址栏的URL地址会改变。

用生活中一个常见的例子来说明两者之间的区别,某人要去办理护照:

转发:小王问小张借5元钱,小张没有,然后小张就问小红借了5元钱给了小王。

重定向:小王问小张借5元钱,小张没有,然后小张告诉小王小红有,所有小王就亲自去问小红借到了
5元。

这里写一个例子演示两者的不同。新建一个web项目,创建三个页面:reg.jsp、response.jsp、request.jsp。

reg.jsp代码如下

1.<body>  2.  <h1>你好</h1><hr>  3.  <form name="regForm" action="response.jsp" method="post">  4.  <table>  5.    <tr>  6.      <td>用户名:</td>  7.      <td><input type="text" name="username"/></td>  8.    </tr>  9.    <tr>  10.       <td colspan="2"><input type="submit" value="提交"/></td>  11.    </tr>  12.  </table>  13.  </form>  14.</body>  

response.jsp代码如下

[html] view plain copy 1.<%  2.    response.setContentType("text/html;charset=utf-8");  3.      4.    out.println("<h1>response内置对象</h1>");  5.    out.println("<hr>");  6.    response.sendRedirect("request.jsp");  7.    //request.getRequestDispatcher("request.jsp").forward(request, response);  8.%>  

request.jsp代码

[html] view plain copy 1.<body>  2.  <h1>request对象</h1><hr>  3.     你是谁?<%=request.getParameter("username") %>  4.  </body>