Shop项目Servlet抽取

本文介绍了一种通过分层提高Servlet复用性的方法,并实现了购物车功能。通过创建BaseServlet并使用反射机制,实现了不同功能的灵活调用。此外,详细展示了ProductServlet中的购物车相关操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

随着项目开发,servlet越来越多,所以分层向上抽取。

创建 productServlet,UserServlet。继承 BaseServlet

BaseServlet利用反射,传递方法名字执行各项功能。

抽取过后修改前端页面各项需要修改的地址即个位.jsp页面,web配置


BaseServlet

package com.itheima.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("all")
public class BaseServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		
		try {
			//1.获得请求的method的名称
			String methodName = request.getParameter("method");
			//2.获得当前被访问对象的字节码对象
			Class clazz = this.getClass();//ProductServlet.class------UserServlet
			//3.获得当前这个字节码对象中的指定方法
			Method method = clazz.getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
			//4. 执行相应的方法
			method.invoke(this, request,response);
		} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			e.printStackTrace();
		}
		
		
	}
}



productServlet抽取结果

package com.itheima.web.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

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

import com.google.gson.Gson;
import com.itheima.domain.Cart;
import com.itheima.domain.CartItem;
import com.itheima.domain.Category;
import com.itheima.domain.PageBean;
import com.itheima.domain.Product;
import com.itheima.service.ProductService;
import com.itheima.utils.JedisPoolUtils;

import redis.clients.jedis.Jedis;

public class ProductServlet extends BaseServlet {

	/*public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获取方法名
		String methodName = request.getParameter("method");
		if (methodName.equals("categoryList")) {
			CategoryList(request, response);
		} else if (methodName.equals("index")) {
			index(request, response);
		} else if (methodName.equals("productInfo")) {
			productInfo(request, response);
		} else if (methodName.equals("productListByCid")) {
			productListByCid(request, response);
		}

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}*/

	// 模块中功能方法的区分
	
	//清空购物车
	public void clearCart(HttpServletRequest request, HttpServletResponse response) throws IOException  {
		HttpSession session = request.getSession();
		session.removeAttribute("cart");
		//跳转回cart.jsp
		response.sendRedirect(request.getContextPath()+"/cart.jsp");
	}
	//在购物车删除购物项
	public void delProFromCart(HttpServletRequest request, HttpServletResponse response) throws IOException  {
		//获取pid
		String pid = request.getParameter("pid");
		//获取购物车项
		HttpSession session = request.getSession();
		Cart cart = (Cart) session.getAttribute("cart");
		if(cart!=null) {
			Map<String, CartItem> cartItems = cart.getCartItems();
			//修改cart的总计
			double total = cart.getTotal()-cartItems.get(pid).getSubtotal();
			cart.setTotal(total);
			//删除购物项
			cartItems.remove(pid);
		}
		//放回session域
		session.setAttribute("cart", cart);
		//跳转回cart.jsp
		response.sendRedirect(request.getContextPath()+"/cart.jsp");
	
	}
	
	
	//将商品添加到购物车
	public void addProductToCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		ProductService service = new ProductService();
		//获得放在购物车商品的pid
		String pid = request.getParameter("pid");
		//获得这次商品的购买数
		int buyNum = Integer.parseInt(request.getParameter("buyNum"));
		//获得paoduct对象
		Product product = service.findProductByPid(pid);
		//计算这次小计
		double subtotal = product.getShop_price()*buyNum;
		/*//封装cartItem
		CartItem carItem = new CartItem();
		carItem.setBuyNum(buyNum);
		carItem.setProduct(product);
		carItem.setSubtotal(subtotal);*/
		
		//获取购物车,判断session中是否已经有购物车 ,没有就创建
		Cart cart = (Cart) session.getAttribute("cart");
		if(cart==null) {
			cart = new Cart();
		}
		//将购物项放到车中---key是pid
		//先判断购物车中是否已将包含此购物项了 ----- 判断key是否已经存在
		//如果购物车中已经存在该商品----将现在买的数量与原有的数量进行相加操作、
		Map<String, CartItem> cartItems = cart.getCartItems();
		double newSubtotal =product.getShop_price()*buyNum;
		if(cartItems.containsKey(pid)) {
			//购物车已经有该商品
			//获取之前的购物车项
			CartItem oldCartItem = cartItems.get(pid);
			//之前和现在相加后的最后购买数量
			buyNum=oldCartItem.getBuyNum()+buyNum;
			//之前和现在相加后的最后购买小计
			newSubtotal=oldCartItem.getSubtotal()+subtotal;
		}
		//封装最终的购物车项
		CartItem carItem = new CartItem();
		carItem.setBuyNum(buyNum);
		carItem.setProduct(product);
		carItem.setSubtotal(newSubtotal);
		
		//将购物项存到购物车中
		cartItems.put(pid, carItem);
		//计算计算购物车总计
		double total = cart.getTotal()+subtotal;
		cart.setTotal(total);
		
		 //车再次放回session
		session.setAttribute("cart", cart);
		//直接跳转到购物车页面
		response.sendRedirect(request.getContextPath()+"/cart.jsp");
	}

	// 1.获取商品分类列表
	public void categoryList(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ProductService service = new ProductService();
		// 先从缓存查看是否存在categoryList 如果没有从数据库查找,再存到redis缓存,如果有,直接调用
		Jedis jedis = JedisPoolUtils.getJedis();
		String categoryListJson = jedis.get("categoryListJson");
		if (categoryListJson == null) {
			System.out.println("缓存没有数据,查找数据库");
			// 获取商品分类
			List<Category> categoryList = service.findAllCategory();
			Gson gson = new Gson();
			categoryListJson = gson.toJson(categoryList);
			jedis.set("categoryListJson", categoryListJson);
		}
		
		/*// 获取商品分类
		List<Category> categoryList = service.findAllCategory();
		Gson gson = new Gson();
		String categoryListJson = gson.toJson(categoryList);*/
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().write(categoryListJson);
	}

	// 2.获取热门商品与最新商品集合
	public void index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ProductService service = new ProductService();
		// 获取热门商品
		List<Product> hotProductList = service.findHotProduct();
		// 获取最新商品
		List<Product> newProductList = service.findNewProduct();
		// 把集合传到域
		request.setAttribute("hotProductList", hotProductList);
		request.setAttribute("newProductList", newProductList);
		// 转发
		request.getRequestDispatcher("/index.jsp").forward(request, response);
	}

	// 3.商品详细信息页面
	public void productInfo(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取pid
		String pid = request.getParameter("pid");
		String cid = request.getParameter("cid");
		String currentPage = request.getParameter("currentPage");
		ProductService service = new ProductService();
		// 根据pid查询商品
		Product product = service.findProductByPid(pid);
		// 根据cid查询分类
		Category category = service.findCategoryByPid(cid);
		// 传到request域,转发
		request.setAttribute("category", category);
		request.setAttribute("product", product);
		request.setAttribute("cid", cid);
		request.setAttribute("currentPage", currentPage);
		// 获得客户端携带的cookie 获得名字pids的cookie
		// 转发前创建cookie,存储pid
		String pids = pid;
		Cookie[] cookies = request.getCookies();
		if (cookies != null) {
			for (int i = 0; i < cookies.length; i++) {
				if ("pids".equals(cookies[i].getName())) {
					pids = cookies[i].getValue();
					String[] split = pids.split("-");
					List<String> asList = Arrays.asList(split);
					LinkedList<String> list = new LinkedList<String>(asList);
					// 判断当前集合是否包含现在的pid
					if (list.contains(pid)) {
						// 包含当前商品的pid
						list.remove(pid);
						list.addFirst(pid);
					} else {
						// 不包含当前pid
						list.addFirst(pid);
					}
					// 将集合转为字符串[3,1,2]转为3-1-2
					StringBuffer sb = new StringBuffer();
					for (int j = 0; j < list.size(); j++) {
						sb.append(list.get(j));
						sb.append("-");
					}
					// 去掉最后的-
					pids = sb.substring(0, sb.length() - 1);
				}
			}
		}
		Cookie cookie_pids = new Cookie("pids", pids);
		response.addCookie(cookie_pids);
		request.getRequestDispatcher("/product_info.jsp").forward(request, response);
	}

	// 4.根据分类cid获取商品集合
	public void productListByCid(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获得cid
		String cid = request.getParameter("cid");
		// 获取当前页
		String currentPageStr = request.getParameter("currentPage");
		if (currentPageStr == null) {
			currentPageStr = "1";
		}
		int currentPage = Integer.parseInt(currentPageStr);
		int currentCount = 12;
		// 根据cid找pageBean
		ProductService service = new ProductService();
		PageBean pageBean = service.getPageBeanByCid(cid, currentPage, currentCount);
		// 定义一个手机历史商品的集合
		ArrayList<Product> histroyProductList = 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 (int i = 0; i < split.length && i < 7; i++) {
						Product product = service.findProductByPid(split[i]);
						histroyProductList.add(product);
					}
				}
			}
		}
		request.setAttribute("pageBean", pageBean);
		request.setAttribute("cid", cid);
		request.setAttribute("histroyProductList", histroyProductList);
		request.getRequestDispatcher("product_list.jsp").forward(request, response);
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值