代码仓库+文档:https://gitee.com/DerekAndroid/ServletJDBC.git
分析:
效果:
http://localhost:8080/ServletJDBC_war_exploded/product?method=findAll
1.商品查询
需求:有一个页面上面有一个超链接[查询所有商品],点击[查询所有商品],会把数据库中的所有商品信息查询出来,并且展示在表格中
如何在一个servlet中判断执行哪个方法:
doGet(request,response){
//获取到method的值
//判断method
if("findAll".equals(method)){
//走查询方法
}else if("add".equals(method)){
//走添加方法
}
}
//定义查询方法
//定义增加方法
......
步骤分析:
1.创建数据库和表结构
2.创建动态的web项目,创建包结构,导入项目需要的资源
3.创建一个首页,上面有一个'查询所有商品'的超链接,点击链接后向servlet发送请求 ${pageContext.request.contextPath}/findAll?method=findAll
4.servlet的操作
//获取method
//判断当前method是哪个请求(增删改查)
//编写具体请求的方法
//调用service和dao完成查询数据库所有商品的操作
//返回一个list结合
//把当前的list放入request域对象中
//请求转发到jsp解析
2.增加商品
需求:在首页有个[增加商品]的超链接,点击超链接后,能把用户录入的数据保存到数据库
步骤分析:
1.在首页加一个[添加商品]的超链接 ${pageContext.request.contextPath}/product?method=addUI
2.点击超链接向servlet发送请求 (请求转发到product.jsp中 防止product.jsp直接暴露在地址栏中)
3.用户录入数据后点击增加按钮 向servlet发送请求
${pageContext.request.contextPath}/product?method=add(有丢失参数的风险)
解决方式:<input type="hidden" name="method" value="add">
4.在add方法中
//获取表单中的所有数据 map
//创建product
//把map中的数据拷贝到product中
//把pid(UUID)和pdate存放到Product中
//调用service和dao完成数据保存操作
//请求转发到查询所有的链接上 /product?method=findAll
//如果有异常需要请求转发到error.jsp页面
3.修改商品
需求:点击列表中商品后面的修改按钮,就可以对当前商品信息进行修改,
跳转到修改的表单页面(数据是已经填写好的),在此基础上进行修改,点击修改按钮后,在数据库中更新该条数据
4.删除商品
需求:点击列表中商品后面的删除按钮,点击后,弹出[确认删除该条商品吗?]的提示,点击确认,则删除该条商品,点击取消,不执行删除
5.批量删除商品
6.模糊查询
7.分页
sql表
CREATE DATABASE day17;
USE day17;
CREATE TABLE `product` (
`pid` VARCHAR (96),
`pname` VARCHAR (150),
`market_price` DOUBLE ,
`shop_price` DOUBLE ,
`pimage` VARCHAR (600),
`pdate` DATE ,
`pdesc` VARCHAR (765)
);
INSERT INTO `product` VALUES('1','小米 4c 标准版','1399','1299','products/1/c_0001.jpg','2015-11-02','小米 4c 标准版 全网通 白色 移动联通电信4G手机 双卡双待');
INSERT INTO `product` VALUES('10','华为 Ascend Mate7','2699','2599','products/1/c_0010.jpg','2015-11-02','华为 Ascend Mate7 月光银 移动4G手机 双卡双待双通6英寸高清大屏,纤薄机身,智能超八核,按压式指纹识别!!选择下方“移动老用户4G飞享合约”,无需换号,还有话费每月返还!');
INSERT INTO `product` VALUES('11','vivo X5Pro','2399','2298','products/1/c_0014.jpg','2015-11-02','移动联通双4G手机 3G运存版 极光白【购机送蓝牙耳机+蓝牙自拍杆】新升级3G运行内存·双2.5D弧面玻璃·眼球识别技术');
INSERT INTO `product` VALUES('12','努比亚(nubia)My 布拉格','1899','1799','products/1/c_0013.jpg','2015-11-02','努比亚(nubia)My 布拉格 银白 移动联通4G手机 双卡双待【嗨11,下单立减100】金属机身,快速充电!布拉格相机全新体验!');
INSERT INTO `product` VALUES('13','华为 麦芒4','2599','2499','products/1/c_0012.jpg','2015-11-02','华为 麦芒4 晨曦金 全网通版4G手机 双卡双待金属机身 2.5D弧面屏 指纹解锁 光学防抖');
INSERT INTO `product` VALUES('14','vivo X5M','1899','1799','products/1/c_0011.jpg','2015-11-02','vivo X5M 移动4G手机 双卡双待 香槟金【购机送蓝牙耳机+蓝牙自拍杆】5.0英寸大屏显示·八核双卡双待·Hi-Fi移动KTV');
INSERT INTO `product` VALUES('15','Apple iPhone 6 (A1586)','4399','4288','products/1/c_0015.jpg','2015-11-02','Apple iPhone 6 (A1586) 16GB 金色 移动联通电信4G手机长期省才是真的省!点击购机送费版,月月送话费,月月享优惠,畅享4G网络,就在联通4G!');
Servlet
package com.itheima.servlet;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import com.itheima.bean.Product;
import com.itheima.service.ProductService;
import com.mysql.fabric.xmlrpc.base.Data;
public class ProductServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//解决乱码
request.setCharacterEncoding("utf-8");
//获取method
String method = request.getParameter("method");
//根据method判断执行哪个方法
if("findAll".equals(method)){
findAll(request,response);
}else if("addUI".equals(method)){
addUI(request,response);
}else if("add".equals(method)){
add(request,response);
}else if("edit".equals(method)){
edit(request,response);
}else if("update".equals(method)){
update(request,response);
}else if("delete".equals(method)){
deletePro(request,response);
}
}
/*
* 根据商品id删除商品信息
*/
private void deletePro(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//获取pid
String pid = request.getParameter("pid");
//调用service和dao完成删除商品操作
ProductService ps = new ProductService();
ps.deletePro(pid);
//请求转发到查询所有的链接上
request.getRequestDispatcher("/product?method=findAll").forward(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
request.setAttribute("msg", "删除商品失败");
request.getRequestDispatcher("/error.jsp").forward(request, response);
}
}
/**
* 根据id更新商品
* @param request
* @param response
* @throws IOException
* @throws ServletException
*/
private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//获取map
Map<String, String[]> map = request.getParameterMap();
//创建bean
Product pro = new Product();
//把map中的数据拷贝到bean中
BeanUtils.populate(pro, map);
//调用service完成数据更新
ProductService ps = new ProductService();
ps.updatePro(pro);
//请求转发到查询所有商品的链接上
request.getRequestDispatcher("/product?method=findAll").forward(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
request.setAttribute("msg", "更新商品失败");
request.getRequestDispatcher("/error.jsp").forward(request, response);
}
}
/**
* 根据id查询数据
* @param request
* @param response
* @throws IOException
* @throws ServletException
*/
private void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//获取id
String id = request.getParameter("id");
//调用方法查询pro
ProductService ps = new ProductService();
Product pro=ps.getProByPid(id);
//把pro放入request中
request.setAttribute("pro", pro);
//请求转发到edit.jsp
request.getRequestDispatcher("/edit.jsp").forward(request, response);
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("msg", "查询单条记录商品失败");
request.getRequestDispatcher("/error.jsp").forward(request, response);
}
}
/**
* 添加商品
* @param request
* @param response
* @throws IOException
* @throws ServletException
*/
private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//获取前台录入的数据 map
Map<String, String[]> map = request.getParameterMap();
//创建bean
Product pro = new Product();
//把map中的数据拷贝到bean中
BeanUtils.populate(pro, map);
//把pid和pdate放入bean中
pro.setPid(UUIDCls.getUUid());
pro.setPdate(new Date().toLocaleString());
//调用service完成保存操作
ProductService ps = new ProductService();
ps.saveProduct(pro);
//请求转发到查询链接
request.getRequestDispatcher("/product?method=findAll").forward(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
request.setAttribute("msg", "添加商品失败");
request.getRequestDispatcher("/error.jsp").forward(request, response);
}
}
/**
* 防止具体的资源暴露在地址栏后面
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
private void addUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.getRequestDispatcher("/product.jsp").forward(request, response);
}
/**
* 查询所有商品
* @param request
* @param response
* @throws IOException
* @throws ServletException
*/
private void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//创建ProductService
ProductService ps = new ProductService();
//调用方法
List<Product> list = ps.findAll();
//把list集合放入request域对象中
request.setAttribute("list", list);
//请求转发到list.jsp
request.getRequestDispatcher("/list.jsp").forward(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
request.setAttribute("msg", "查询商品出现错误");
request.getRequestDispatcher("/error.jsp").forward(request, response);
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}