案例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 ...
随机推荐
- js调试工具Console命令详解——转
一.显示信息的命令 <!DOCTYPE html> <html> <head> <title>常用console命令</title> < ...
- Quartus中代码字体大小的调整方法
Quartus中代码大小的调整方法 网友 "一纸玫瑰"整理 第一步:点击Tools(工具) 第二步:点击Options(选项) 第三步:Text Editor(文本编辑)/Font ...
- java爬虫入门
本文内容 涞源于 罗刚 老师的 书籍 << 自己动手写网络爬虫一书 >> ; 本文将介绍 1: 网络爬虫的是做什么的? 2: 手动写一个简单的网络爬虫; 1: 网络爬虫是做 ...
- DNS被污染后
如果有条件,自已DNS还是非常必要的,至少有一亩三分地的净土. 但是DNS污染是无处不在的,特别是 Forwarding的记录, 一旦 IPv6 Tunnel连接失败,DNS Server 瞬间就被 ...
- delphi数组之菜鸟篇
数组是可以通过索引来引用的同类型数据的列表.按照存储空间的获取方式,Delphi支持的数组类型有两种,即静态数组和动态数组.所谓静态数组就是在声明时就已经确定大小的数组类型,而动态数组是指其大小在声明 ...
- vmware虚拟机监控数据
在vsphere产品中内建一个监控所有虚机包括主机资源的插件,叫做vcenter servcie status,这个插件的主要功能是记录当前虚拟机资源的cpu.硬盘.内存和网络等相关信息.通过它可以查 ...
- jenkins+docker+docker machine 远程部署
dotnet publish -c Release docker build -t microtest:1.0 --build-arg microport=1000 -f "$WORKSPA ...
- 忘记Oracle用户名和密码
方法一: 看看是不是Oracle服务器没有打开 打开cmd,输入sqlplus /nolog,回车---->进入sqlplus; 输入“conn /as sysdba”:以超级管理员的方式连接数 ...
- 记一次 Confluence 被攻击事件
故事开始 4 月 14 日,星期天,天气不好,呆在家玩 LOL,正 Happy 的时候同事打电话给我,说 Confluence 看文档的时候挂了,报错:502. 一寻思,不就挂了吗,小意思,重启呗,于 ...
- pandas set_index() reset_index()
set_index() 官方定义: 使用一个或多个现有列设置索引, 默认情况下生成一个新对象 DataFrame.set_index(keys, drop=True, append=False, ...