案例25-servlet的抽取
1 product模块的抽取版本一
1 ProductServlet代码
抽取之后,原来对应的IndexServlet,ProductListByCidServlet等都可以删除。对应的web.xml里面的配置文件也需要删除。
然后就是需要修改原来页面中执行对应servlet的代码。
package www.test.web.servlet; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; 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 com.google.gson.Gson; import redis.clients.jedis.Jedis; import www.test.domain.Category; import www.test.domain.Product; import www.test.service.ProductService; import www.test.utils.JedisPoolUtils; import www.test.vo.PageBean; public class ProductServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获得请求的哪个方法method String methodName = request.getParameter("method"); //防止非空,将productListByCid放在前面,这样就能避免 if("productListByCid".equals(methodName)){ productListByCid(request,response); }else if("categoryList".equals(methodName)){ categoryList(request,response); }else if("index".equals(methodName)){ index(request,response); }else if("productInfo".equals(methodName)){ productInfo(request,response); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } // 模块中的方法是通过方法名进行区分的 // 1 显示商品类别的功能 public void categoryList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ProductService service = new ProductService(); // 先从缓存中查询categoryList 如果有直接使用 没有在从数据库中查询 存到缓存中 // 1、获得jedis对象 连接redis数据库 Jedis jedis = JedisPoolUtils.getJedis(); String categoryListJson = jedis.get("categoryListJson"); // 2、判断categoryListJson是否为空 if (categoryListJson == null) { System.out.println("缓存没有数据 查询数据库"); // 准备分类数据 List<Category> categoryList = null; try { categoryList = service.findAllCategory(); } catch (SQLException e) { e.printStackTrace(); } // 使用转换工具将categoryList转换成json格式 Gson gson = new Gson(); categoryListJson = gson.toJson(categoryList); // 将从数据库中获得的categoryListJson存储到缓存中 jedis.set("categoryListJson", categoryListJson); } // 将转换后的json格式字符串写出 // 写出前先解决乱码问题 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> List<Product> hotProductList = null; try { hotProductList = service.findHotProductList(); } catch (SQLException e) { e.printStackTrace(); } // 获取最新商品-----List<Product> List<Product> newProductList = null; try { newProductList = service.findNewProductList(); } catch (SQLException e) { e.printStackTrace(); } // 准备分类数据 /* * List<Category> categoryList =null; try { categoryList = * service.findAllCategory(); } catch (SQLException e) { * * e.printStackTrace(); } request.setAttribute("categoryList", * categoryList); */ // 将获取的数据存入request域 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 { // 获取cid和当前页 String cid = request.getParameter("cid"); String currentPage = request.getParameter("currentPage"); // 获取pid String pid = request.getParameter("pid"); // 传递给service层并调取service层的方法 ProductService service = new ProductService(); Product product = null; try { product = service.findProductByPid(pid); } catch (SQLException e) { e.printStackTrace(); } // 存储到request域中 request.setAttribute("product", product); request.setAttribute("cid", cid); request.setAttribute("currentPage", currentPage); // 获取客户端携带的cookie----获得名字是pids的cookie String pids = pid; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if ("pids".equals(cookie.getName())) { pids = cookie.getValue(); // 1-3-2 本次访问的商品的pid是8----->8-1-3-2 // 1-3-2 本次访问的商品的pid是3----->3-1-2 // 1-3-2 本次访问的商品的pid是1----->2-1-3 // 将pids拆成一个数组 String[] split = pids.split("-");// {3,1,2} // 数组转换成集合 List<String> asList = Arrays.asList(split);// [3,1,2] LinkedList<String> list = new LinkedList<String>(asList); // [3,1,2] // 判断集合中是否存在当前的pid /* * if(list.contains(pid)){ //包含当前查看的商品的pid //先删掉然后放在头上 * list.remove(pid); list.addFirst(pid); }else{ * //不包含当前查看的商品的pid 直接将该pid放在头上 list.addFirst(pid); } */ // 上面代码的优化 // 不管包不包含都需要放到头上 if (list.contains(pid)) { // 包含当前查看的商品的pid list.remove(pid); } list.addFirst(pid); // 将[3,1,2]转成3-1-2字符串 StringBuffer sb = new StringBuffer(); for (int i = 0; i < list.size() && i < 7; ++i) { sb.append(list.get(i)); sb.append("-"); // 3-1-2- } // 去掉3-1-2-后面的- // substring包含头不包含尾 pids = sb.substring(0, sb.length() - 1); } } } // 创建cookie回写 Cookie cookie_pids = new Cookie("pids", pids); cookie_pids.setMaxAge(60 * 60); // 单位为秒 设置cookie的存储事件一个小时 // 设置cookie的携带路径 cookie_pids.setPath(request.getContextPath()); // 将cookie_pids写回去 response.addCookie(cookie_pids); // 转发 request.getRequestDispatcher("/product_info.jsp").forward(request, response); } // 4 根据商品的类别获得商品的列表 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查询商品 ProductService service = new ProductService(); PageBean<Product> pageBean = service.findProductListByCid(cid,currentPage,currentCount); request.setAttribute("pageBean", pageBean); request.setAttribute("cid", cid); //定义一个集合记录历史商品信息的集合 List<Product> historyProductList = 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(); //3-1-2 String[] split = pids.split("-"); for(String pid:split){ Product product =null; try { product = service.findProductByPid(pid); historyProductList.add(product); } catch (SQLException e) { e.printStackTrace(); } } } } } //将历史记录的集合放到域中 request.setAttribute("historyProductList", historyProductList); //转发 request.getRequestDispatcher("/product_list.jsp").forward(request, response); } }
2 页面中代码的修改
将原来访问的servlet改成访问ProductServlet,需要访问的方法以get的方式提交过去。
2 product模块的抽取版本二
版本二中对ProductServlet中方法的调用进行抽取。
1 ProductServlet代码
package www.test.web.servlet; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; 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 com.google.gson.Gson; import redis.clients.jedis.Jedis; import www.test.domain.Category; import www.test.domain.Product; import www.test.service.ProductService; import www.test.utils.JedisPoolUtils; import www.test.vo.PageBean; public class ProductServlet extends BaseServlet { /*public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获得请求的哪个方法method String methodName = request.getParameter("method"); //防止非空,将productListByCid放在前面,这样就能避免 if("productListByCid".equals(methodName)){ productListByCid(request,response); }else if("categoryList".equals(methodName)){ categoryList(request,response); }else if("index".equals(methodName)){ index(request,response); }else if("productInfo".equals(methodName)){ productInfo(request,response); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }*/ // 模块中的方法是通过方法名进行区分的 // 1 显示商品类别的功能 public void categoryList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ProductService service = new ProductService(); // 先从缓存中查询categoryList 如果有直接使用 没有在从数据库中查询 存到缓存中 // 1、获得jedis对象 连接redis数据库 Jedis jedis = JedisPoolUtils.getJedis(); String categoryListJson = jedis.get("categoryListJson"); // 2、判断categoryListJson是否为空 if (categoryListJson == null) { System.out.println("缓存没有数据 查询数据库"); // 准备分类数据 List<Category> categoryList = null; try { categoryList = service.findAllCategory(); } catch (SQLException e) { e.printStackTrace(); } // 使用转换工具将categoryList转换成json格式 Gson gson = new Gson(); categoryListJson = gson.toJson(categoryList); // 将从数据库中获得的categoryListJson存储到缓存中 jedis.set("categoryListJson", categoryListJson); } // 将转换后的json格式字符串写出 // 写出前先解决乱码问题 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> List<Product> hotProductList = null; try { hotProductList = service.findHotProductList(); } catch (SQLException e) { e.printStackTrace(); } // 获取最新商品-----List<Product> List<Product> newProductList = null; try { newProductList = service.findNewProductList(); } catch (SQLException e) { e.printStackTrace(); } // 准备分类数据 /* * List<Category> categoryList =null; try { categoryList = * service.findAllCategory(); } catch (SQLException e) { * * e.printStackTrace(); } request.setAttribute("categoryList", * categoryList); */ // 将获取的数据存入request域 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 { // 获取cid和当前页 String cid = request.getParameter("cid"); String currentPage = request.getParameter("currentPage"); // 获取pid String pid = request.getParameter("pid"); // 传递给service层并调取service层的方法 ProductService service = new ProductService(); Product product = null; try { product = service.findProductByPid(pid); } catch (SQLException e) { e.printStackTrace(); } // 存储到request域中 request.setAttribute("product", product); request.setAttribute("cid", cid); request.setAttribute("currentPage", currentPage); // 获取客户端携带的cookie----获得名字是pids的cookie String pids = pid; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (Cookie cookie : cookies) { if ("pids".equals(cookie.getName())) { pids = cookie.getValue(); // 1-3-2 本次访问的商品的pid是8----->8-1-3-2 // 1-3-2 本次访问的商品的pid是3----->3-1-2 // 1-3-2 本次访问的商品的pid是1----->2-1-3 // 将pids拆成一个数组 String[] split = pids.split("-");// {3,1,2} // 数组转换成集合 List<String> asList = Arrays.asList(split);// [3,1,2] LinkedList<String> list = new LinkedList<String>(asList); // [3,1,2] // 判断集合中是否存在当前的pid /* * if(list.contains(pid)){ //包含当前查看的商品的pid //先删掉然后放在头上 * list.remove(pid); list.addFirst(pid); }else{ * //不包含当前查看的商品的pid 直接将该pid放在头上 list.addFirst(pid); } */ // 上面代码的优化 // 不管包不包含都需要放到头上 if (list.contains(pid)) { // 包含当前查看的商品的pid list.remove(pid); } list.addFirst(pid); // 将[3,1,2]转成3-1-2字符串 StringBuffer sb = new StringBuffer(); for (int i = 0; i < list.size() && i < 7; ++i) { sb.append(list.get(i)); sb.append("-"); // 3-1-2- } // 去掉3-1-2-后面的- // substring包含头不包含尾 pids = sb.substring(0, sb.length() - 1); } } } // 创建cookie回写 Cookie cookie_pids = new Cookie("pids", pids); cookie_pids.setMaxAge(60 * 60); // 单位为秒 设置cookie的存储事件一个小时 // 设置cookie的携带路径 cookie_pids.setPath(request.getContextPath()); // 将cookie_pids写回去 response.addCookie(cookie_pids); // 转发 request.getRequestDispatcher("/product_info.jsp").forward(request, response); } // 4 根据商品的类别获得商品的列表 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查询商品 ProductService service = new ProductService(); PageBean<Product> pageBean = service.findProductListByCid(cid,currentPage,currentCount); request.setAttribute("pageBean", pageBean); request.setAttribute("cid", cid); //定义一个集合记录历史商品信息的集合 List<Product> historyProductList = 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(); //3-1-2 String[] split = pids.split("-"); for(String pid:split){ Product product =null; try { product = service.findProductByPid(pid); historyProductList.add(product); } catch (SQLException e) { e.printStackTrace(); } } } } } //将历史记录的集合放到域中 request.setAttribute("historyProductList", historyProductList); //转发 request.getRequestDispatcher("/product_list.jsp").forward(request, response); } }
2 BaseServlet代码
package www.test.web.servlet; import java.io.IOException; import java.lang.reflect.Method; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class BaseServlet extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //解决乱码问题 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); try { // 1 获得请求的method方法 String methodName = request.getParameter("method"); // 2获得当前被访问的对象的字节码对象 Class clazz = this.getClass(); //ProductServlet.class --- UserServlet.class // 3 获取当前字节码对象中指定的方法 Method method = clazz.getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class); // 4 执行相应的方法 method.invoke(this, request,response); } catch (Exception e) { e.printStackTrace(); } } }
其他代码和版本一一样