学习过程:
下面我们需要完成的是商品管理,虽然也是增删改查这个几个功能,不过因为需要上传商品图和分页两个功能,而且商品也和类别有多对一的关系,所以商品管理相比之下就比较复杂一点,不过也没有关系,这方便的知识点我们前面也已经讲过了。
1、完成dao层。注意分页的代码,这里用到了Page类,这个类可在源码中获得。
public class GoodsDao extends BaseDao implements IGoodsDao {
/**
* 添加商品
*
* @param goods
* @return
*/
public int add(Goods goods) {
int result = 0;
getCon();
String sql = "insert into goods(type_id,goods_name,cash,infos,pic,nums) values(?,?,?,?,?,?)";
result = exeUpdate(
sql,
new Object[] { goods.getTypeId(), goods.getGoodsName(),
goods.getCash(), goods.getInfos(), goods.getPic(),
goods.getNums() });
closeAll();
return result;
}
/**
* 根据Id删除商品
*
* @param id
* @return
*/
public int del(int id) {
int result = 0;
getCon();
String sql = "delete from goods where goods_id=?";
result = exeUpdate(sql, new Object[] { id });
closeAll();
return result;
}
/**
* 更新商品信息
*
* @param goods
* @return
*/
public int update(Goods goods) {
int result = 0;
getCon();
String sql = "update goods set type_id=?,goods_name=?,cash=?,infos=?,pic=?,nums=? where goods_id=?";
result = exeUpdate(
sql,
new Object[] { goods.getTypeId(), goods.getGoodsName(),
goods.getCash(), goods.getInfos(), goods.getPic(),
goods.getNums(), goods.getGoodsId() });
closeAll();
return result;
}
/**
* 根据商品Id获得单个商品信息
*
* @param id
* @return
*/
public Goods getById(int id) {
Goods goods = null;
getCon();
String sql = "select * from goods where goods_id=?";
rs = exeQuery(sql, new Object[] { id });
try {
if (rs.next()) {
goods = new Goods();
goods.setCash(rs.getDouble("cash"));
goods.setGoodsId(rs.getInt("goods_id"));
goods.setGoodsName(rs.getString("goods_name"));
goods.setInfos(rs.getString("infos"));
goods.setNums(rs.getInt("nums"));
goods.setPic(rs.getString("pic"));
goods.setTypeId(rs.getInt("type_id"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
closeAll();
}
return goods;
}
/**
* 根据商品类型分页显示商品信息列表
*
* @param typeId
* 商品类别ID
* @param page
* 分页信息
* @return
*/
public List getByType(int typeId, Page page) {
List goodses = new ArrayList();
getCon();
try {
String sqlcount = "select count(*) from goods where type_id=?";
rs = exeQuery(sqlcount, new Object[] { typeId });
if (rs.next()) {
page.setItmeCount(rs.getInt(1));
}
String sql = "select * from goods where type_id=? limit ?,?";
//String sql="select * from(select t.*,rownum rn from(select * from goods where type_id=? order by goods_id desc) t where rownum<=?) where rn>? ";
rs = exeQuery(sql,new Object[] { typeId, page.getItemStart(),page.getPageSize() });
while (rs.next()) {
Goods goods = new Goods();
goods.setCash(rs.getDouble("cash"));
goods.setGoodsId(rs.getInt("goods_id"));
goods.setGoodsName(rs.getString("goods_name"));
goods.setInfos(rs.getString("infos"));
goods.setNums(rs.getInt("nums"));
goods.setPic(rs.getString("pic"));
goods.setTypeId(rs.getInt("type_id"));
goodses.add(goods);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeAll();
}
return goodses;
}
}
2、实现控制层也就是servlet层。需要注意的地方是,在列表页面、添加页面和修改页面都需要把商品类别显示出来,所有这些方法都需查询所有的类别,并放到request作用域中。还有就是在删除数据库的商品时,注意应该把商品图片也删除了,这样可以节省空间。
public class GoodsServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
IGoodsDao goodsDao=FactoryDao.getInstanse().newGoodsDao();
IGoodsTypesDao goodsTypesDao=FactoryDao.getInstanse().newGoodsTypesDao();
String ope = request.getParameter("ope");
if (ope == null || ope.equals("list")) {// 商品列表
int cpage = 1;
int tid = 0;
// 获得所有的类别
List goodsTypeses = goodsTypesDao.getAllTypes();
String cpagestr = request.getParameter("cpage");
String tidstr = request.getParameter("tid");
if (cpagestr != null) {
cpage = Integer.parseInt(cpagestr);
}
if (tidstr == null) {
tid = goodsTypeses.get(0).getTypeId();
} else {
tid = Integer.parseInt(tidstr);
}
Page page = new Page();
page.setCurrentPage(cpage);
page.setPageSize(5);
List goodses = goodsDao.getByType(tid, page);
request.setAttribute("goodses", goodses);
request.setAttribute("goodsTypeses", goodsTypeses);
request.setAttribute("page", page);
request.setAttribute("tid", tid);
request.getRequestDispatcher("goodslist.jsp").forward(request,
response);
} else if (ope.equals("toadd")) {// 进入添加商品页
List goodsTypeses = goodsTypesDao.getAllTypes();
request.setAttribute("goodsTypeses", goodsTypeses);
request.getRequestDispatcher("goodsadd.jsp").forward(request,
response);
} else if (ope.equals("add")) {// 执行添加
Map forMap = new HashMap();
String filename = null;
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString("utf-8");
forMap.put(name, value);
} else {
String fieldname = item.getFieldName();
filename = item.getName();
// UUID唯一值
filename = UUID.randomUUID()
+ filename.substring(filename.indexOf("."));
String path = request.getSession().getServletContext()
.getRealPath("/");
File uploadFile = new File(path + "/uploadfile/"
+ filename);
item.write(uploadFile);
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Goods goods = new Goods();
goods.setGoodsName(forMap.get("goodsName"));
goods.setTypeId(Integer.parseInt(forMap.get("typeId")));
goods.setCash(Double.parseDouble(forMap.get("cash")));
goods.setInfos(forMap.get("infos"));
goods.setNums(Integer.parseInt(forMap.get("nums")));
goods.setPic(filename);
int result = goodsDao.add(goods);
if (result > 0) {
response.sendRedirect("GoodsServlet");
} else {
response.sendRedirect("error.jsp");
}
} else if (ope.equals("del")) {// 执行删除
// 获得要删除id
int gid = Integer.parseInt(request.getParameter("gid"));
int result = goodsDao.del(gid);
if (result > 0) {
response.sendRedirect("GoodsServlet");
} else {
response.sendRedirect("error.jsp");
}
} else if (ope.equals("toupdate")) {// 进入更新
List goodsTypeses = goodsTypesDao.getAllTypes();
int gid = Integer.parseInt(request.getParameter("gid"));
Goods goods = goodsDao.getById(gid);
request.setAttribute("goods", goods);
request.setAttribute("goodsTypeses", goodsTypeses);
request.getRequestDispatcher("goodsupdate.jsp").forward(request,
response);
} else if (ope.equals("update")) {// 执行更新
//修改 商品
//如果用户没有选择新的图片 》》 不能修改数据库里 商品 pic 属性 》》 使用原先的值
//如果用户选择新的图片 >> 1、修改数据库 2、删除原来的文件
Map forMap = new HashMap();
String filename = null;
//服务器路径
String path = request.getSession()
.getServletContext().getRealPath("/");
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString("utf-8");
forMap.put(name, value);
} else {
String fieldname = item.getFieldName();
filename = item.getName();
// UUID唯一值
// 如果用户上传了新的图片,那么要把原来的图片删除
if (filename != "" || !filename.equals("")
|| filename != null) {
filename = UUID.randomUUID()
+ filename.substring(filename.indexOf("."));
File uploadFile = new File(path + "/uploadfile/"
+ filename);
item.write(uploadFile);
}
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Goods goods = new Goods();
int gid=Integer.parseInt(forMap.get("goodsId"));
Goods temp=goodsDao.getById(gid);//原来保存在数据库中的信息
goods.setGoodsId(gid);
goods.setGoodsName(forMap.get("goodsName"));
goods.setTypeId(Integer.parseInt(forMap.get("typeId")));
goods.setCash(Double.parseDouble(forMap.get("cash")));
goods.setInfos(forMap.get("infos"));
goods.setNums(Integer.parseInt(forMap.get("nums")));
//如果用户没有上传新的图片
if (filename == "" || filename.equals("") || filename == null) {
goods.setPic(temp.getPic());
} else {
//删除文件
File file=new File(path+"/uploadfile/"+temp.getPic());
file.delete();
goods.setPic(filename);
}
int result = goodsDao.update(goods);
if (result > 0) {
response.sendRedirect("GoodsServlet");
} else {
response.sendRedirect("error.jsp");
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
页面代码比较多,也比较简单,这里就不全部显示出来的,大家可以参考源码实现。今天的任务还需要完成后台的用户管理的,这部分内容和商品管理类似,留给大家作为作业吧。
这里还用到日期格式化的标签:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
下面列出商品列表的代码: