之前寒假写的一个小项目,idea写的,用了maven工程,Spring+SpringMVC+MyBatis框架技术实现校园超市系统。
我的博客:www.jiaxuan.fun
之前加的人有点多,源码+sql+jar已上传到 https://download.csdn.net/download/qq_38663663/11076831
里边的sql放错了,正确的:链接:https://pan.baidu.com/s/1rhUfNyA4LmHpjTsxzVbvcw ji
提取码:3760
同时也可以加我的QQ:354124728 互相交流一下升仙经验。。。
1、数据库表:
item表:商品详情
order:订单
product:商品
product_type:商品类型
role:身份管理
sysuser:系统管理员
user:用户表
2、界面展示:
3、项目目录:
super_parent:父目录
super_common:公共目录(存放工具类、异常、常量等)
super_pojo:实体类
super_dao:数据访问层
super_service:业务层
super_base_web:Web模块——后台管理系统
因为全写篇幅太长,所以挑出一个模块来做实例,其余差不多
4.1、Product
package com.market.pojo;
import java.io.Serializable;
public class Product implements Serializable{
private Integer id;
private String batch;
private String name;
private Integer saleNumber;
private Integer number;
private Double price;
private String info;
private String image;
private ProductType productType;
private String pDate;
public Integer getSaleNumber() {
return saleNumber;
}
public void setSaleNumber(Integer saleNumber) {
this.saleNumber = saleNumber;
}
public String getBatch() {
return batch;
}
public void setBatch(String batch) {
this.batch = batch;
}
public String getpDate() {
return pDate;
}
public void setpDate(String pDate) {
this.pDate = pDate;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public ProductType getProductType() {
return productType;
}
public void setProductType(ProductType productType) {
this.productType = productType;
}
}
4.2、ProductDao
package com.market.dao;
import com.market.pojo.Product;
import org.apache.commons.fileupload.FileUploadException;
import java.util.List;
/**
* @Auther:jiaxuan
* @Date: 2019/2/21 0021 13:02
* @Description:
*/
public interface ProductDao {
public void insert(Product product);
//int insert(Product product);
Product selectByName(String name);
List selectAll();
Product selectById(int id);
int update(Product product);
void deleteById(int id);
}
ProductMapper.xml
id,
batch,
name,
number,
price,
info,
image,
product_type_id,
p_date
insert into t_product
(id,batch,name,number , price,info, image, product_type_id,p_date)
values
(#{id},#{batch},#{name},#{number},#{price},#{info},#{image},#{productType.id},#{pDate})
update t_product
batch=#{batch},
name=#{name},
sale_number=#{sale_number},
number=#{number},
price=#{price},
info=#{info},
image=#{image},
product_type_id=#{product_type_id},
where id=#{id}
delete from t_product
where id=#{id}
4.3、ProductService
ProductService接口:
package com.market.service;
import com.market.dto.ProductDto;
import com.market.pojo.Product;
import org.apache.commons.fileupload.FileUploadException;
import java.io.OutputStream;
import java.util.List;
/**
* @Auther:jiaxuan
* @Date: 2019/2/20 0020 16:21
* @Description:
*/
public interface ProductService {
//public int add(Product product);
public void add(ProductDto productDto) throws FileUploadException;
boolean checkName(String name);
List findAll();
Product findById(int id);
void modify(ProductDto productDto) throws FileUploadException;
void getImage(String path, OutputStream outputStream);
public void updateNum(Product product);
void removeById(int id);
}
实现类:
package com.market.service.Impl;
import com.market.common.util.StringUtils;
import com.market.dao.ProductDao;
import com.market.dto.ProductDto;
import com.market.pojo.Product;
import com.market.pojo.ProductType;
import com.market.service.ProductService;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.fileupload.FileUploadException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StreamUtils;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
/**
* @Auther:jiaxuan
* @Date: 2019/2/20 0020 16:35
* @Description:
*/
@Service
/**
* 声明式事务
* 1.如果存在一个事务,则支持当前事务。如果没有事务则开启
* 2.事物在遇到非运行时异常时也回滚
*/
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class ProductServiceImpl implements ProductService {
@Autowired
private ProductDao productDao;
@Override
public void add(ProductDto productDto) throws FileUploadException {
//1.文件上传
String fileName = StringUtils.renameFileName(productDto.getFileName());
String filePath = productDto.getUploadPath()+"/"+fileName;
try {
StreamUtils.copy(productDto.getInputStream(),new FileOutputStream(filePath));
} catch (IOException e) {
//e.printStackTrace();
throw new FileUploadException("文件上传失败"+e.getMessage());
}
//2.保存到数据库,将DTO转换为PO
Product product = new Product();
try {
PropertyUtils.copyProperties(product,productDto);
product.setImage(filePath);
ProductType productType = new ProductType();
productType.setId(productDto.getProductTypeId());
product.setProductType(productType);
productDao.insert(product);
} catch (Exception e) {
e.printStackTrace();
}
}
// @Override
// public int add(Product product) {
// return productDao.insert(product);
// }
@Override
public boolean checkName(String name) {
Product product = productDao.selectByName(name);
if (product!=null){
return false;
}
return true;
}
@Override
public List findAll() {
return productDao.selectAll();
}
@Override
public Product findById(int id) {
return productDao.selectById(id);
}
@Override
public void modify(ProductDto productDto) throws FileUploadException {
// 1.文件上传
String fileName = StringUtils.renameFileName(productDto.getFileName());
String filePath=productDto.getUploadPath()+"/"+fileName;
try {
StreamUtils.copy(productDto.getInputStream(),new FileOutputStream(filePath));
} catch (IOException e) {
throw new FileUploadException("文件上传失败"+e.getMessage());
}
// 2.保存到数据库,将DTO转换为PO
Product product = new Product();
try {
PropertyUtils.copyProperties(product,productDto);
product.setImage(filePath);
ProductType productType = new ProductType();
productType.setId(productDto.getProductTypeId());
product.setProductType(productType);
productDao.update(product);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取图片,写到输出流中
* @param path
* @param outputStream
*/
@Override
public void getImage(String path, OutputStream outputStream) {
try {
StreamUtils.copy(new FileInputStream(path),outputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void updateNum(Product product) {
productDao.update(product);
}
@Override
public void removeById(int id) {
productDao.deleteById(id);
}
}
4.4、ProductBase
ProductController
package com.market.controller;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.market.common.constant.PageConstant;
import com.market.common.constant.ResponseStatusConstant;
import com.market.common.exception.ProductTypeExistsException;
import com.market.common.util.DateUtil;
import com.market.common.util.ResponsResult;
import com.market.dto.ProductDto;
import com.market.pojo.Product;
import com.market.pojo.ProductType;
import com.market.service.ProductService;
import com.market.service.ProductTypeService;
import com.market.vo.ProductVo;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.fileupload.FileUploadException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Auther:jiaxuan
* @Date: 2019/2/20 0020 14:44
* @Description:
*/
@Controller
@RequestMapping("/base/product")
public class ProductController {
@Autowired
private ProductService productService;
@Autowired
private ProductTypeService productTypeService;
@ModelAttribute("productTypes")
public List loadProductTypes() {
List productTypes = productTypeService.findEnable();
return productTypes;
}
@RequestMapping("/findAll")
public String findAll(Integer pageNum, Model model){
if (pageNum==null) {
pageNum = PageConstant.PAGE_NUM;
}
PageHelper.startPage(pageNum,PageConstant.PAGE_SIZE);
List products = productService.findAll();
PageInfo pageInfo = new PageInfo(products);
model.addAttribute("pageInfo", pageInfo);
return "productManager";
}
@RequestMapping("/findInfo")
public String findInfo(Integer pageNum, Model model){
if (pageNum==null) {
pageNum = PageConstant.PAGE_NUM;
}
PageHelper.startPage(pageNum,PageConstant.PAGE_SIZE_FRONT);
List products = productService.findAll();
PageInfo pageInfo = new PageInfo(products);
model.addAttribute("pageInfo", pageInfo);
return "productInfo";
}
@RequestMapping("/findSale")
public String findSale(Integer pageNum, Model model){
if (pageNum==null) {
pageNum = PageConstant.PAGE_NUM;
}
PageHelper.startPage(pageNum,PageConstant.PAGE_SIZE_FRONT);
List products = productService.findAll();
PageInfo pageInfo = new PageInfo(products);
model.addAttribute("pageInfo", pageInfo);
return "productSale";
}
// @RequestMapping("/add")
// @ResponseBody
// public String add(HttpServletRequest request, @RequestParam("file") MultipartFile file,String fileName,
// Product product,Model model) throws Exception{
// Date day = new Date();
// SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
// String batch = df.format(day).toString()+String.valueOf((int)(Math.random()*9000+1000));
// ProductType productType = new ProductType();
//
// product.setProductType(productType);
// product.setpDate(DateUtil.getCurrentDateStr());
// product.setImage(fileName);
// product.setBatch(batch);
// productService.add(product);
// //如果文件不为空,写入上传路径
// if(!file.isEmpty()) {
// //上传文件路径
// String path = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
// //上传文件名
// String filename = fileName;
// File filepath = new File(path,filename);
// //判断路径是否存在,如果不存在就创建一个
// if (!filepath.getParentFile().exists()) {
// filepath.getParentFile().mkdirs();
// }
// //将上传文件保存到一个目标文件当中
// file.transferTo(new File(path + File.separator + filename));
// return "forward:findAll";
// } else {
// return "forward:findAll";
// }
// }
//C:\Program Files\Apache Software Foundation\Tomcat 9.0\webapps\ROOT\WEB-INF\images
@RequestMapping("/add")
public String add(ProductVo productVo, HttpSession session,Integer pageNum,Model model){
String uploadPath = session.getServletContext().getRealPath("/WEB-INF/images");
System.out.println(uploadPath);
try {
ProductDto productDto = new ProductDto();
Date day = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
String batch = df.format(day).toString()+String.valueOf((int)(Math.random()*9000+1000));
//对象属性间的拷贝
PropertyUtils.copyProperties(productDto,productVo);
productDto.setBatch(batch);
productDto.setpDate(DateUtil.getCurrentDateStr());
productDto.setInputStream(productVo.getFile().getInputStream());
productDto.setFileName(productVo.getFile().getOriginalFilename());
productDto.setUploadPath(uploadPath);
productService.add(productDto);
model.addAttribute("successMsg","添加成功");
} catch (Exception e) {
model.addAttribute("errorMsg",e.getMessage());
}
return "forward:findAll";
}
/**
* 检测名称是否已经存在
*/
@RequestMapping("/checkName")
@ResponseBody
public Map checkName(String name) {
Map map = new HashMap<>();
if (productService.checkName(name)) { //不存在,可用
map.put("valid", true);
} else {
map.put("valid", false);
map.put("message", "商品(" + name + ")已存在");
}
return map;
}
@RequestMapping("/findById")
@ResponseBody
public ResponsResult findById(int id){
Product product = productService.findById(id);
return ResponsResult.success(product);
}
@RequestMapping("/getImage")
public void getImage(String path, OutputStream outputStream) {
productService.getImage(path, outputStream);
}
@ResponseBody
@RequestMapping("/updateNumber")
public Map updateNumber(Product product){
Map result = new HashMap<>();
Product productNumber = productService.findById(product.getId());
product.setSaleNumber(product.getNumber());
Integer number = productNumber.getNumber() - product.getNumber();
if (number>0){
product.setNumber(number);
}else {
result.put("success",false);
result.put("errorInfo","商品数量不足");
return result;
}
productService.updateNum(product);
result.put("success", true);
return result;
}
@RequestMapping("/removeById")
@ResponseBody
public ResponsResult removeById(int id){
productService.removeById(id);
return ResponsResult.success();
}
}
4.5、Spring-dao.xml
mysql
4.6、Spring-mvc.xml
10485760
UTF-8
4.7、Spring-service.xml
4.8、dataSource.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/supermarket?useUnicde=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=你密码
jdbc.initialSize=5
4.9、Web.xml
springMVC
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring*.xml
1
springMVC
/
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
utf-8
encodingFilter
/*
4.10、ProductMananger
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
base
商品管理
图片
编号
商品批次号
商品
数量
价格
商品详情
产品类型
状态
生产日期
操作
${product.id}
${product.batch}
${product.name}
${product.number}
${product.price}
${product.info}
${product.productType.name}
有效商品
无效商品
${product.pDate}