今天我们来实现我们项目的下一个模块,商品模块
和分类模块类似,我们也需要进行商品的增删改查,但在此基础上我们的商品还有和分类有所关联,并且还要上传图片,所以我们先把图片上传的工具类写下吧。
package com.imooc.utils;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
* 文件上传的工具类
*
*/
public class UploadUtils {
/**
* 生成唯一的文件名:
*/
public static String getUUIDFileName(String fileName){
// 将文件名的前面部分进行截取:xx.jpg ---> .jpg
int idx = fileName.lastIndexOf(".");
String extention = fileName.substring(idx);
String uuidFileName = UUID.randomUUID().toString().replace("-", "")+extention;
return uuidFileName;
}
public static Map uploadFile(HttpServletRequest request) throws IOException {
Map<String,String> map = new HashMap<String,String>();
// 1.创建一个磁盘文件项工厂对象
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
// 2.创建一个核心解析类
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
// 3.解析request请求,返回的是List集合,List集合中存放的是FileItem对象
String url = null;
String uuidFileName= null;
try {
List<FileItem> list = servletFileUpload.parseRequest(request);
for (FileItem fileItem : list) {
if(fileItem.isFormField()){
// 不是文件上传
// 接收表单项参数的值:
String name = fileItem.getFieldName(); // 获得表单项的name属性的值
String value = fileItem.getString("UTF-8");// 获得表单项的值
// 存入集合
map.put(name, value);
}else{
// 文件上传
// 文件上传项:
// 文件上传功能:
// 获得文件上传的名称:
String fileName = fileItem.getName();
System.out.println("filename="+fileName);
if(fileName !=null && !"".equals(fileName)){
// 通过工具类获得唯一文件名:
uuidFileName = UploadUtils.getUUIDFileName(fileName);
// 获得文件上传的数据:
InputStream is = fileItem.getInputStream();
// 获得文件上传的路径:
String path = request.getServletContext().getRealPath("/upload");
// 将输入流对接到输出流就可以了:
url = path+"\\"+uuidFileName;
OutputStream os = new FileOutputStream(url);
int len = 0;
byte[] b = new byte[1024];
while((len = is.read(b))!=-1){
os.write(b, 0, len);
}
is.close();
os.close();
map.put("path", request.getContextPath()+"/upload/"+uuidFileName);
map.put("filename", fileName);
}
System.out.println(map);
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
return map;
}
public static void main(String[] args) {
System.out.println(getUUIDFileName("1.jpg"));
}
}
接下来是Servlet层
package com.imooc.web.action;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.imooc.domain.Category;
import com.imooc.domain.Product;
import com.imooc.service.CategoryService;
import com.imooc.service.ProductService;
import com.imooc.service.impl.CategoryServiceImpl;
import com.imooc.service.impl.ProductServiceImpl;
import com.imooc.utils.UploadUtils;
@WebServlet("/ProductServlet")
public class ProductServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//接收method的参数
String methodName=request.getParameter("method");
if("findAll".equals(methodName)) {
findAll(request,response);
}else if("saveUI".equals(methodName)) {
saveUI(request,response);
}else if("save".equals(methodName)) {
save(request,response);
}else if("edit".equals(methodName)) {
edit(request,response);
}else if("update".equals(methodName)) {
update(request,response);
}else if("delete".equals(methodName)) {
delete(request,response);
}
}
/**
* 后台商品管理,商品模块的删除
* @param request
* @param response
* @throws IOException
*/
private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
// TODO Auto-generated method stub
Integer pid=Integer.parseInt(request.getParameter("pid"));
ProductService productService=new ProductServiceImpl();
//查询商品信息
Product product=productService.findOne(pid);
String path=product.getPath();
if(path!=null&&!"".equals(path)) {
String realPath=this.getServletContext().getRealPath(path);
System.out.println(realPath);
File file=new File(realPath);
if(file.exists())
file.delete();
}
productService.delete(pid);
//页面跳转
response.sendRedirect(request.getContextPath()+"/ProductServlet?method=findAll");
}
/**
* 后台商品管理,修改商品的方法
* @param request
* @param response
* @throws IOException
*/
private void update(HttpServletRequest request, HttpServletResponse response) throws IOException {
// 接收数据
Map<String ,String> map=UploadUtils.uploadFile(request);
//封装数据
Product product=new Product();
product.setPid(Integer.parseInt(map.get("pid")));
product.setPname(map.get("pname"));
product.setAuthor(map.get("author"));
product.setPrice(Double.parseDouble(map.get("price")));
product.setDescription(map.get("description"));
product.setFilename(map.get("filename"));
product.getCategory().setCid(Integer.parseInt(map.get("cid")));
product.setPath(map.get("path"));
//处理数据
ProductService productService=new ProductServiceImpl();
productService.update(product);
//页面跳转
response.sendRedirect(request.getContextPath()+"/ProductServlet?method=findAll");
}
/**
* 后台管理,修改商品的方法
* @param request
* @param response
* @throws IOException
* @throws ServletException
*/
private void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//接收数据
Integer pid=Integer.parseInt(request.getParameter("pid"));
//调用业务层处理数据
ProductService productService=new ProductServiceImpl();
Product product=productService.findOne(pid);
System.out.println(product);
CategoryService categoryService=new CategoryServiceImpl();
List<Category> categorylist=categoryService.findAll();
//页面跳转
request.setAttribute("product", product);
request.setAttribute("categoryList", categorylist);
request.getRequestDispatcher("/admin/product_update.jsp").forward(request, response);
}
/**
* 后台商品管理,保存商品的方法
* @param request
* @param response
* @throws IOException
*/
private void save(HttpServletRequest request, HttpServletResponse response) throws IOException {
System.out.println("sadasdasd save");
//文件上传
Map<String, String> map=UploadUtils.uploadFile(request);
//将数据完成封装
Product product=new Product();
product.setPname(map.get("pname"));
product.setAuthor(map.get("author"));
product.setPrice(Double.parseDouble(map.get("price")));
product.setDescription(map.get("description"));
product.setFilename(map.get("filename"));
product.getCategory().setCid(Integer.parseInt(map.get("cid")));
product.setPath(map.get("path"));
//处理数据
ProductService productService=new ProductServiceImpl();
productService.save(product);
//页面跳转
response.sendRedirect(request.getContextPath()+"/ProductServlet?method=findAll");
}
/**
* 商品模块,跳转到开发页面
* @param request
* @param response
* @throws IOException
* @throws ServletException
*/
private void saveUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//查询所有分类的信息
CategoryService categoryService=new CategoryServiceImpl();
List<Category> list=categoryService.findAll();
//页面跳转
request.setAttribute("categoryList", list);
request.getRequestDispatcher("/admin/product_add.jsp").forward(request, response);
}
/**
* 商品模块,查询所有商品的方法
* @param request
* @param response
* @throws IOException
* @throws ServletException
*/
private void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//不接收参数
System.out.println("productServlet的findAll方法执行");
//调用业务层处理数据
ProductService productService=new ProductServiceImpl();
List<Product> list=productService.findAll();
for(Product p:list){
System.out.println(p.toString());
}
//页面跳转
request.setAttribute("list", list);
request.getRequestDispatcher("/admin/product_list.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
然后是service层接口和其实现
package com.imooc.service;
import java.util.List;
import com.imooc.domain.PageBean;
import com.imooc.domain.Product;
public interface ProductService {
List<Product> findAll();
void save(Product product);
Product findOne(Integer pid);
void update(Product product);
void delete(Integer pid);
PageBean<Product> findByPage(int page);
}
package com.imooc.service.impl;
import java.util.List;
import com.imooc.dao.ProductDao;
import com.imooc.dao.impl.ProductDaoImpl;
import com.imooc.domain.PageBean;
import com.imooc.domain.Product;
import com.imooc.service.ProductService;
public class ProductServiceImpl implements ProductService {
@Override
public List<Product> findAll() {
System.out.println("product service impl");
ProductDao productDao=new ProductDaoImpl();
return productDao.findAll();
}
@Override
public void save(Product product) {
// TODO Auto-generated method stub
ProductDao productDao=new ProductDaoImpl();
productDao.save(product);
}
@Override
public Product findOne(Integer pid) {
// TODO Auto-generated method stub
ProductDao productDao=new ProductDaoImpl();
return productDao.findOne(pid);
}
@Override
public void update(Product product) {
// TODO Auto-generated method stub
ProductDao productDao=new ProductDaoImpl();
productDao.update(product);
}
@Override
public void delete(Integer pid) {
ProductDao productDao=new ProductDaoImpl();
productDao.delete(pid);
}
@Override
public PageBean<Product> findByPage(int page) {
PageBean<Product> pageBean=new PageBean<Product>();
//封装数据
pageBean.setPage(page);
int limit=2;
pageBean.setLimit(limit);
ProductDao productDao=new ProductDaoImpl();
int totalCount=productDao.findCount();//记录总记录数
pageBean.setTotalCount(totalCount);
System.out.println("totalcount"+totalCount);
int totalPage= totalCount%limit ==0? totalCount/limit:(totalCount/limit+1);
System.out.println("totalPage"+totalPage);
pageBean.setTotalPage(totalPage);
int begin=(page-1)*limit;
List<Product> list=productDao.findByPage(begin,limit);
pageBean.setList(list);
return pageBean;
}
}
然后是Dao层接口和其实现
package com.imooc.dao;
import java.sql.Connection;
import java.util.List;
import com.imooc.domain.Product;
public interface ProductDao {
List<Product> findAll();
void save(Product product);
Product findOne(Integer pid);
void update(Product product);
void delete(Integer pid);
List<Product> findByCid(Integer cid);
void update(Connection conn, Product p);
int findCount();
List<Product> findByPage(int begin, int limit);
}
package com.imooc.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.imooc.dao.ProductDao;
import com.imooc.domain.Product;
import com.imooc.utils.JDBCUtils;
public class ProductDaoImpl implements ProductDao {
@Override
public List<Product> findAll() {
System.out.println("product dao");
// TODO Auto-generated method stub
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
List<Product> list = null;
try {
conn = JDBCUtils.getConnection();
String sql = "select * from product p,category c where p.cid=c.cid order by p.pid desc";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
list = new ArrayList<Product>();
while (rs.next()) {
Product product = new Product();
product.setPid(rs.getInt("pid"));
product.setPname(rs.getString("pname"));
product.setAuthor(rs.getString("author"));
product.setPrice(rs.getDouble("price"));
product.setDescription(rs.getString("description"));
product.setFilename(rs.getString("filename"));
product.setPath(rs.getString("path"));
product.getCategory().setCid(rs.getInt("cid"));
product.getCategory().setCname(rs.getString("cname"));
product.getCategory().setCdesc(rs.getString("cdesc"));
list.add(product);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(rs, pstmt, conn);
}
return list;
}
@Override
public void save(Product product) {
// TODO Auto-generated method stub
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = JDBCUtils.getConnection();
String sql = "insert into product values(null,?,?,?,?,?,?,?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, product.getPname());
pstmt.setString(2, product.getAuthor());
pstmt.setDouble(3, product.getPrice());
pstmt.setString(4, product.getDescription());
pstmt.setString(5, product.getFilename());
pstmt.setString(6, product.getPath());
pstmt.setInt(7, product.getCategory().getCid());
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(pstmt, conn);
}
}
@Override
public Product findOne(Integer pid) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
String sql = "select * from product p,category c where p.cid=c.cid and pid=?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, pid);
rs = pstmt.executeQuery();
if (rs.next()) {
Product product = new Product();
product.setPid(rs.getInt("pid"));
product.setPname(rs.getString("pname"));
product.setAuthor(rs.getString("author"));
product.setPrice(rs.getDouble("price"));
product.setDescription(rs.getString("description"));
product.setFilename(rs.getString("filename"));
product.setPath(rs.getString("path"));
product.getCategory().setCid(rs.getInt("cid"));
product.getCategory().setCname(rs.getString("cname"));
product.getCategory().setCdesc(rs.getString("cdesc"));
return product;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(rs, pstmt, conn);
}
return null;
}
@Override
public void update(Product product) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = JDBCUtils.getConnection();
String sql = "update product set pname=?,author=?,price=?,description=?,filename=?,path=?,cid=? where pid=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, product.getPname());
pstmt.setString(2, product.getAuthor());
pstmt.setDouble(3, product.getPrice());
pstmt.setString(4, product.getDescription());
pstmt.setString(5, product.getFilename());
pstmt.setString(6, product.getPath());
pstmt.setObject(7, product.getCategory().getCid());
pstmt.setInt(8, product.getPid());
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(pstmt, conn);
}
}
@Override
public void delete(Integer pid) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = JDBCUtils.getConnection();
String sql = "delete from product where pid=?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, pid);
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(pstmt, conn);
}
}
@Override
public List<Product> findByCid(Integer cid) {
System.out.println("product dao");
// TODO Auto-generated method stub
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
List<Product> list = null;
try {
conn = JDBCUtils.getConnection();
String sql = "select * from product p,category c where p.cid=c.cid and p.cid=? order by p.pid desc";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, cid);
rs = pstmt.executeQuery();
list = new ArrayList<Product>();
while (rs.next()) {
Product product = new Product();
product.setPid(rs.getInt("pid"));
product.setPname(rs.getString("pname"));
product.setAuthor(rs.getString("author"));
product.setPrice(rs.getDouble("price"));
product.setDescription(rs.getString("description"));
product.setFilename(rs.getString("filename"));
product.setPath(rs.getString("path"));
product.getCategory().setCid(rs.getInt("cid"));
product.getCategory().setCname(rs.getString("cname"));
product.getCategory().setCdesc(rs.getString("cdesc"));
list.add(product);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(rs, pstmt, conn);
}
return list;
}
@Override
public void update(Connection conn, Product product) {
PreparedStatement pstmt = null;
try {
String sql = "update product set pname=?,author=?,price=?,description=?,filename=?,path=?,cid=? where pid=?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, product.getPname());
pstmt.setString(2, product.getAuthor());
pstmt.setDouble(3, product.getPrice());
pstmt.setString(4, product.getDescription());
pstmt.setString(5, product.getFilename());
pstmt.setString(6, product.getPath());
pstmt.setObject(7, product.getCategory().getCid());
pstmt.setInt(8, product.getPid());
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(pstmt!=null)
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public int findCount() {
System.out.println("product dao");
// TODO Auto-generated method stub
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
Long num=0l;
try {
conn = JDBCUtils.getConnection();
String sql = "select count(*) as c from product";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
if (rs.next()) {
num=rs.getLong("c");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(rs, pstmt, conn);
}
return num.intValue();
}
@Override
public List<Product> findByPage(int begin, int limit) {
System.out.println("product dao");
// TODO Auto-generated method stub
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
List<Product> list = null;
try {
conn = JDBCUtils.getConnection();
String sql = "select * from product limit ?,?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, begin);
pstmt.setInt(2, limit);
rs = pstmt.executeQuery();
list = new ArrayList<Product>();
while (rs.next()) {
Product product = new Product();
product.setPid(rs.getInt("pid"));
product.setPname(rs.getString("pname"));
product.setAuthor(rs.getString("author"));
product.setPrice(rs.getDouble("price"));
product.setDescription(rs.getString("description"));
product.setFilename(rs.getString("filename"));
product.setPath(rs.getString("path"));
list.add(product);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.release(rs, pstmt, conn);
}
return list;
}
}
实现效果如下所示
活着或许是一种恩赐
但是也许活着也就让人觉得筋疲力尽了
但也总归因为活着,第二天早上起来,还是会有很好的天气,渐暖的微风,熟悉的笑脸,其实这也许也就够了吧。
是吧。
加油!!!
看都看了,
老铁来个3连
点赞关注转发,来一波
666666