由这张图就可以明显看出转发和重定向的区别:
转发是一次响应一次请求
重定向是两次转发两次请求
因此在转发中servlet中东西,在b.jsp中都能使用,所以我们在使用转发时,如果要在b.jsp中使用一些相关的属性,就可以使用request.setAttribute(string key,string value );的形式,在b.jsp中就可以直接使用了,地址栏也不会发生任何改变
重定向是直接跳转到你指定的页面去,当a.jsp找到一个servlet,然后servlet就向客户响应一个respons方法(所以为什么重定向就是response.sendRedirct())当servlet向客户端响应了,然后客户端就知道去请求哪一个页面了,因此就直接跳转到你响应的页面去,所以这就是为什么两次响应两次请求了。当然,b.jsp也不能共享servlet中相应的东西。so 他的地址栏就会发生改变
举一个例子:当点击返回页面时,
其找相应的servlet:(代码)
<div>
<a href="${pageContext.request.contextPath }/Product?method=productListByCid&cid=${cid }¤tPage=${currentPage }">返回列表页面</a>
</div>
找打相应的servlet:
public void productListByCid(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ProductService service = new ProductService();
// 获得cid
String cid = request.getParameter("cid");
// 在点击商品的分页时 把当前页传递过来
String currentPageStr = request.getParameter("currentPage");
// 如果刚开始加载数据时 并没有把当前页传递过来 所以要进行判断
if (currentPageStr == null) {
currentPageStr = "1";
}
int currentPage = Integer.parseInt(currentPageStr);
int currentCount = 12;
PageBean pageBean = service.findProductBycid(cid, currentPage, currentCount);
request.setAttribute("pageBean", pageBean);
request.setAttribute("cid", cid);
// 定义一个记录历史信息的集合
List<Product> historyProduct = new ArrayList<Product>();
// 获得客户端携带名字叫pids的cookie
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("pids".equals(cookie.getName())) {
String pids = cookie.getValue();
String[] split = pids.split("-");
for (String pid : split) {
Product pro = service.findProductBypid(pid);
historyProduct.add(pro);
}
}
}
}
// 将历史记录存放在转发域中
request.setAttribute("historyProduct", historyProduct);
// 转发
request.getRequestDispatcher("/product_list.jsp").forward(request, response);
}
当点击的时候,地址就是相应的servlet
我们就可以来看一下 product_list.jsp也同时在调用相应的servlet中的属性
重定向后面来补!