页面跳转的时候有两种方式即:重定向与转发
重定向:
response.sendRedirect(“地址”);
a. 页面地址显示最终页面
b. 不可向后传递参数
c. 跳到外部站点
服务器转发:
request.getRequestDispatcher(“地址”).forward(request, response);
a. 页面地址显示请求页面
b. 可以向后传递参数
c. 不可以跳到外部站点
这里写一个例子演示两者的不同。新建一个web项目,创建三个页面:reg.jsp、response.jsp、request.jsp。
reg.jsp代码如下:
<body>
<h1>你好</h1><hr>
<form name="regForm" action="response.jsp" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="提交"/></td>
</tr>
</table>
</form>
</body>
这里输入用户名,然后交给response.jsp处理。
response.jsp代码如下:
<%
response.setContentType("text/html;charset=utf-8");
out.println("<h1>response内置对象</h1>");
out.println("<hr>");
response.sendRedirect("request.jsp");
//request.getRequestDispatcher("request.jsp").forward(request, response);
%>
首先,使用重定向交给request.jsp来处理。
response.jsp代码如下:
<body>
<h1>request对象</h1><hr>
你是谁?<%=request.getParameter("username") %>
</body>
使用重定向时,结果如下:
可以看到,输入的用户名没有显示出来,这是因为重定向本质上相当于两次请求,而前一次请求不保存,所以没能得到用户名。同时,可以看到地址栏中的URL地址由response.jsp变为了request.jsp。
第二次,修改response.jsp的代码如下:
<%
response.setContentType("text/html;charset=utf-8");
out.println("<h1>response内置对象</h1>");
out.println("<hr>");
//response.sendRedirect("request.jsp");
request.getRequestDispatcher("request.jsp").forward(request, response);
%>
使用转发,将请求转发给request.jsp来处理,结果如下:
可以看到,页面得到了请求中的用户名并进行显示,这是由于转发时客户端只有一次请求,服务器会保存这次请求,等到转发返回时将结果返回给客户端。同时,页面显示的是request.jsp的内容,但地址栏中的URL地址并没有变化。
参考:http://blog.csdn.net/u012877472/article/details/50804568
http://blog.csdn.net/chen757576314/article/details/44836327