案例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();
}
} }
其他代码和版本一一样
案例25-servlet的抽取的更多相关文章
- servlet的抽取
servlet的抽取 servlet按照模块来划分,比如注册和登录的servlet就放到user的servlet中 原来: 登录时登录的servlet 注册时注册的servlet 现在: 登录注册的s ...
- Maven项目- Servlet的抽取和优化 java.lang.NoSuchMethodException 的解决方法
优化servlet,减少servlet的数量,便于开发与维护.现在是一个功能一个Servlet,将其优化为一个模块一个Servlet,BaseServlet的抽取和优化,相当于在数据库中一张表对应一个 ...
- java 随机抽取案例,不重复抽取
以学生类为例,先准备一个Student类 package cn.sasa.demo1; public class Student { private int id; private String na ...
- 简易的CRM系统案例之Servlet+Jsp+MySQL版本
数据库配置 datebase.properties driver=com.mysql.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/infos usernam ...
- 类的反射实例(servlet的抽取)
类的反射实例 具体以后我们写的时候不用写BaseServlet,因为各种框架都已经给我们写好了 所以,user对应的servlet的界面长这样:
- 浅谈JavaWEB入门必备知识之Servlet入门案例详解
工欲善其事.必先利其器,想要成为JavaWEB高手那么你不知道servlet是一个什么玩意的话,那就肯定没法玩下去,那么servlet究竟是个什么玩意?下面,仅此个人观点并通过一个小小的案例来为大家详 ...
- servlet中的过滤器 国际化
1. 过滤器 基本概念 过滤器是需要在xml中配置的. 为什么需用到过滤器? 项目开发中,经常会涉及到重复代码的实现! 注册 ----à Servlet [1. 设置编码] ----à JSP 修改 ...
- 25个最佳的 WordPress Gallery 画廊插件
WordPress 画廊插件最适合用于作品展示网站,特别对于那些想以一个奇特的,现代的方式展示他们作品的摄影师.如果你想为你安装 WordPress Gallery 插件,那么下面的是你想要的. 本文 ...
- 25款专业的 WordPress 电子商务网站主题
WordPress 作为最流行的博客系统,插件众多,易于扩充功能.安装和使用都非常方便,而且有许多第三方开发的免费模板,安装方式简单易用.这篇文章和大家分享35款专业的 WordPress 电子商务网 ...
- 经典案例:那些让人赞不绝口的创新 HTML5 网站
在过去的10年里,网页设计师使用 Flash.JavaScript 或其他复杂的软件和技术来创建网站.但现在你可以前所未有的快速.轻松地设计或创造互动的.有趣好看的网站.如何创建?答案是 HTML5 ...
随机推荐
- Android colorAccent、colorPrimary、colorPrimaryDark actionbar toolbar navigationbar
伴随着Android5.0的发布也更新了support-v7-appcompat 到V21,其中增加了ToolBar.recyclerview.cardview等控件. Android5.0对改变AP ...
- Vue.js的库,包,资源的列表大全。
官方资源 外部资源 社区 播客 官方示例 入门 开发工具 语法高亮 代码片段 自动补全 组件集合 库和插件 路由 ajax/数据 状态管理 校验 UI组件 i18n 示例 模板 脚手架 整合 插件/指 ...
- Android-广播概念
Android中的消息机制 1.Handler+Message消息机制,是用于子线程与主线程的通讯: 2.广播+广播接收者也是消息机制,是重量级别的,四大组件之一,需要激活组件,是用于组件和组件之间通 ...
- Verilog MIPS32 CPU(一)-- PC寄存器
Verilog MIPS32 CPU(一)-- PC寄存器 Verilog MIPS32 CPU(二)-- Regfiles Verilog MIPS32 CPU(三)-- ALU Verilog M ...
- SlidesJS基本使用方法和官方文档解释
Slides – 是一个简单的,容易定制和风格化,的jQuery幻灯片插件. Slides提供褪色或幻灯片过渡效果,图像淡入淡出,图像预压,自动生成分页,循环,自动播放的自定义等很多选项. 用Slid ...
- Android之常用开发框架
1.Rajawali介绍:安卓的OpenGL ES 2.0/3.0 引擎.可以用于制作普通应用或者动态壁纸,当然也可以用于制作游戏.项目地址: https://github.com/Rajawali/ ...
- 构建基于asp.net core 的docker应用并发布
发布Docker镜像的方法有很多种,asp.net core的发布需要在windows系统中 开门见山,首先保证已经在Centos上安装好了Docker.创建一个asp.net core的webapi ...
- C#中IO操作
using sysytem.Io; File.Exists() 检查文件是否存在, Directory.Exists() 检查文件夹是否存在 FileInfo DirectoryInfo 可实例化 对 ...
- DEV 之 有些控件不允许拖动。
DEV 之 有些控件不允许拖动. 设置一个参数即可解决问题
- 使用bmfont制作字体
本地显示正常 将制作好的字体上传 别人用不好使 制作完场景没ctrl+s 保存 ctrl+s保存之后生成另外的文件