页面跳转方式和分页

377 阅读2分钟

这是我参与2022首次更文挑战的第27天,活动详情查看:2022首次更文挑战

1.页面跳转的两种方式

image.png 转发是一次响应一次请求,重定向是两次转发两次请求

因此在转发中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 他的地址栏就会发生改变

<div>
    <a href="${pageContext.request.contextPath }/Product?method=productListByCid&cid=${cid }&currentPage=${currentPage }">返回列表页面</a>
</div>
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);
 
	}

2.分页

要显示一个商品的分页 首先我们要封装一个页的pageBean(由图 很显然我们要包含商品信息List 当前页currentPage  总页数TotalPage  当前页所含商品总个数currentCount  商品总个数totalCount),要想获得分页我们需要在service层将PageBean的信息封装起来返回到web层

public PageBean findProductBycid(String cid, int currentPage, int currentCount) {
		ProductDao dao = new ProductDao();
		// 封装一个pagebean返回到web层
		PageBean<Product> pageBean = new PageBean<Product>();
		// 1.封装当前页
 
		pageBean.setCurrentPage(currentPage);
 
		// 2.每页显示的条数
 
		pageBean.setCurrentCount(currentCount);
 
		// 3.封装总条数
		int totalCount = 0;
		try {
			totalCount = dao.getTotal(cid);
		} catch (SQLException e) {
 
			e.printStackTrace();
		}
		pageBean.setTotalCount(totalCount);
		// 4.封装总页数
		// ceil函数向上取整
		int totalPage = (int) Math.ceil(1.0 * totalCount / currentCount);
		pageBean.setTotalPage(totalPage);
 
		// 5.当前页显示数据
		List<Product> list = null;
		// 当前页与起始索引的关系
		int index = (currentPage - 1) * currentCount;
		try {
			list = dao.findProductBypage(cid, index, currentCount);
		} catch (SQLException e) {
 
			e.printStackTrace();
		}
		pageBean.setList(list);
		return pageBean;
	}