基于javaweb+mysql的jsp+servlet婚品婚纱商城系统(java+servlet+jsp+javascript+mysql)
运行环境
Java≥8、MySQL≥5.7、Tomcat≥8
开发工具
eclipse/idea/myeclipse/sts等均可配置运行
适用
课程设计,大作业,毕业设计,项目练习,学习演示等
功能说明
基于javaweb+mysql的JSP+Servlet婚品婚纱商城系统(java+servlet+jsp+javascript+mysql)
一、项目运行
运行环境
jdk8+tomcat8+mysql+IntelliJ IDEA( Eclispe , MyEclispe ,Sts 都支持,代码与开发环境运行无关啦,只需要调整环境即可)
项目技术
Servlet、JSP 、、MySQL 、 Ajax 、JavaScript、CSS、等等
}
}
//登录过滤器
@WebFilter(filterName = "f2" , urlPatterns = "/order/*")
public class LoginFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest)servletRequest;
HttpServletResponse response = (HttpServletResponse)servletResponse;
//获取会话对象
HttpSession session = request.getSession();
//从会话中获取登录者的信息
User user = (User)session.getAttribute("user");
//若user为null,则直接跳转至登录界面
if(user==null){
response.sendRedirect("login.jsp");
return;
}
//若user不为null,则直接将过滤链传递下去
filterChain.doFilter(request,response);
}
@Override
public void destroy() {
}
}
@WebServlet(urlPatterns = "/user")
public class UserServlet extends BaseServlet {
private UserService service = new UserService();
//注册
public void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获得页面表单中的数据
Map<String, String[]> map = request.getParameterMap();
//封装User对象
User user = new User();
//时间转换器:将String-->Date
ConvertUtils.register(new Converter() {
@Override
public Object convert(Class type, Object o) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = sdf.parse(o.toString());
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
//uid 用户编号
String uid = CommonUtils.getUUID().replaceAll("-","");
user.setUid(uid);
//code 激活码
String code = CommonUtils.getUUID().replaceAll("-","");
user.setCode(code);
//将密码加密存储
user.setPassword(MD5Utils.md5(user.getPassword()));
//执行service中的注册逻辑
boolean flag = service.regist(user);
if(flag){
//注册成功,跳转到registSuccess.jsp
//发送邮件(包含激活码)
String emailMsg = "恭喜您注册成功,请复制此链接打开激活" +
"http://localhost:8888/user?method=active&code="+code+"'";
try {
MailUtils.sendMail(user.getEmail(),"邮件激活",emailMsg);
} catch (MessagingException e) {
e.printStackTrace();
}
request.getRequestDispatcher("registSuccess.jsp").forward(request,response);
}else{
//注册失败,跳转到registFail.jsp
request.getRequestDispatcher("registFail.jsp").forward(request,response);
}
}
//账户激活
public void active(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//根据激活码code,修改状态state
String code = request.getParameter("code");
//调用service进行修改状态
boolean flag = service.active(code);
if(flag){
//激活成功
response.sendRedirect("index.jsp");
}else{
//激活失败
response.sendRedirect("error.jsp");
}
}
//校验用户名是否存在
String page = request.getParameter("pageNow");
//默认查询第一页
int pageNow = 1;
if (page != null) {
pageNow = Integer.parseInt(page);
}
HttpSession session = request.getSession();
User user = (User) session.getAttribute("user");
if (user != null) {
PageVO<Orders> vo = service.viewMyOrders(user.getUid(), pageNow);
List<Orders> ordersList = vo.getList();
if (ordersList != null) {
for (Orders orders : ordersList) {
List<Map<String, Object>> mapList = service.viewOrderItem(orders.getOid());
for (Map<String, Object> map : mapList) {
//订单明细
OrderItem orderItem = new OrderItem();
//商品信息
Product product = new Product();
try {
BeanUtils.populate(orderItem, map);
BeanUtils.populate(product, map);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
//将商品信息装配至订单明细
orderItem.setProduct(product);
//将订单明细装配至订单
orders.getItemsList().add(orderItem);
}
}
}
request.setAttribute("vo", vo);
}
request.getRequestDispatcher("order-list.jsp").forward(request, response);
}
}
orderItem.setProduct(cartItem.getProduct());
//设置所属订单
orderItem.setOrders(orders);
//设置订单中的多个订单明细
orders.getItemsList().add(orderItem);
}
//提交订单
boolean flag = service.submitOrder(orders);
if (flag) {
//提交成功
session.setAttribute("orders", orders);
response.sendRedirect("order.jsp");
} else {
//提交失败
request.setAttribute("msg", "当前订单提交失败,请重新提交");
request.getRequestDispatcher("cart.jsp").forward(request, response);
}
}
//确认订单
public void confirmOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.收集表单数据
Map<String, String[]> map = request.getParameterMap();
HttpSession session = request.getSession();
Orders orders = (Orders) session.getAttribute("orders");
//1.支付验签成功,修改订单支付状态
OrderService service = new OrderService();
int i = service.updateOrderState(orders.getOid());
//2.清除会话中的购物车信息和订单信息
if(i>0){
session.removeAttribute("cart");
session.removeAttribute("orders");
}
//3.跳转至我的订单列表
response.sendRedirect(request.getContextPath()+"/order?method=viewMyOrders");
}
@WebServlet(name = "AdminServlet", urlPatterns = "/admin")
@MultipartConfig
public class AdminServlet extends BaseServlet {
public static String imageUploadPath = "C:\\Users\\Administrator\\Desktop\\200.ye\\project\\web\\img\\product\\";
private AdminService service = new AdminService();
//登录
public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String adminName = request.getParameter("adminName");
String adminPwd = request.getParameter("adminPwd");
HttpSession session = request.getSession();
Admin admin = service.login(adminName, adminPwd);
if (admin != null) {
session.setAttribute("admin", admin);
response.sendRedirect(request.getContextPath() + "/admin/home/home.jsp");
} else {
request.setAttribute("msg", "用户名或密码不匹配");
request.getRequestDispatcher(request.getContextPath() + "/admin/adminlogin.jsp").forward(request, response);
}
}
//登出
public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
session.invalidate();
response.sendRedirect(request.getContextPath() + "/admin/adminlogin.jsp");
}
for (Map<String, Object> map : mapList) {
Date pdate = (Date) map.get("pdate");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(pdate);
map.put("date", date);
}
}
Gson gson = new Gson();
String json = gson.toJson(mapList);
response.getWriter().write(json);
}
//删除信息
public void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String code = request.getParameter("code");
String[] ids = request.getParameterValues("id");
//执行
service.delete(code, ids);
switch (code) {
case "user":
//若code是user时,跳转到会员查询所有页面
response.sendRedirect(request.getContextPath() + "/admin?method=findAll&code=user");
break;
case "product":
//若code是product时,跳转到商品查询所有页面
response.sendRedirect(request.getContextPath() + "/admin?method=findAll&code=product");
break;
case "order":
//若code是order时,跳转到订单查询所有页面
response.sendRedirect(request.getContextPath() + "/admin?method=findAll&code=order");
break;
case "category":
//若code是order时,跳转到订单查询所有页面
response.sendRedirect(request.getContextPath() + "/admin?method=findAll&code=category");
break;
}
}
//上架商品
//删除当前购物项
public void delCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String pid = request.getParameter("pid");
//1.从会话中获取购物车
HttpSession session = request.getSession();
Cart cart = (Cart)session.getAttribute("cart");
//2.获取购物车中的map集合(购物车明细)
Map<String, CartItem> cartMap = cart.getMap();
//3.重新计算总金额 = 原来购物车的总金额 - 当前移除的购物项的小计
double total = cart.getTotal() - cartMap.get(pid).getSubTotal();
//4.购物车移除当前购物项
cartMap.remove(pid);
//5.封装Cart对象
cart.setTotal(total);
//6.添加至会话中
session.setAttribute("cart",cart);
//7.跳转cart.jsp 避免重复提交表单
response.sendRedirect("cart.jsp");
}
//清空购物车
public void clearCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
//清除会话中的购物车信息
session.removeAttribute("cart");
response.sendRedirect("cart.jsp");
}
}
@WebServlet(urlPatterns = "/user")
public class UserServlet extends BaseServlet {
private UserService service = new UserService();
//注册
public void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获得页面表单中的数据
Map<String, String[]> map = request.getParameterMap();
//封装User对象
User user = new User();
//时间转换器:将String-->Date
ConvertUtils.register(new Converter() {
@Override
public Object convert(Class type, Object o) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = sdf.parse(o.toString());
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}, Date.class);
//excel的名字
String fileName = "goods.xls";
//sheet页的名字
String sheetName = "商品详情";
//当前页码
int pageNow = Integer.parseInt(request.getParameter("pageNow"));
//数据
List<Product> goods = service.findAll("product", "", pageNow).getList();
HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, prop, goods, null);
//输出文件
response.setContentType("application/octet-stream;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.addHeader("Pargam", "no-cache");
response.addHeader("Cache-Control", "no-cache");
OutputStream os = response.getOutputStream();
wb.write(os);
os.flush();
os.close();
}
//首页
public void showIndex(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<HomeVO> list = service.findNumByMonth();
Gson gson = new Gson();
String json = gson.toJson(list);
response.getWriter().write(json);
}
//添加和修改商品类别
public void updateCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String code = request.getParameter("code");
Category category = new Category();
if (code.equals("add")) { //添加商品类别
category.setCid(CommonUtils.getUUID().replace("-", ""));
} else if (code.equals("update")) {
category.setCid(request.getParameter("cid"));
}
category.setCname(request.getParameter("cname"));
service.updateCategory(code, category);
response.sendRedirect(request.getContextPath() + "/admin?method=findAll&code=category");
}
}
//注册失败,跳转到registFail.jsp
request.getRequestDispatcher("registFail.jsp").forward(request,response);
}
}
//账户激活
public void active(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//根据激活码code,修改状态state
String code = request.getParameter("code");
//调用service进行修改状态
boolean flag = service.active(code);
if(flag){
//激活成功
response.sendRedirect("index.jsp");
}else{
//激活失败
response.sendRedirect("error.jsp");
}
}
//校验用户名是否存在
public void validateName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
boolean flag = service.validateName(username);
String json = "{\"flag\":"+flag+"}";
response.getWriter().write(json);
}
//登录
public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String username = request.getParameter("username");
String password = request.getParameter("password");
String code = request.getParameter("code");
//不是自动登录
if(code==null){
password = MD5Utils.md5(password);
}
User user = service.login(username, password);
if(user!=null){
//当前会话中是否存在正在添加的商品
if(cartItemMap.containsKey(pid)){
int oldNum = cartItemMap.get(pid).getBuyNum();
//合并后的总数量
buyNum += oldNum;
//当前合并后,重新计算小计
newSubTotal = buyNum * product.getShop_price();
}
//封装CartItem购物车明细
CartItem cartItem = new CartItem(product,buyNum,newSubTotal);
//封装购物车
cartItemMap.put(pid,cartItem);
//将购物车明细添加进来
cart.setMap(cartItemMap);
//将总金额添加进来
double total = cart.getTotal() + subTotal;
cart.setTotal(total);
session.setAttribute("cart",cart);
response.sendRedirect("cart.jsp");
}
//删除当前购物项
public void delCart(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String pid = request.getParameter("pid");
//1.从会话中获取购物车
HttpSession session = request.getSession();
Cart cart = (Cart)session.getAttribute("cart");
//2.获取购物车中的map集合(购物车明细)
Map<String, CartItem> cartMap = cart.getMap();
//3.重新计算总金额 = 原来购物车的总金额 - 当前移除的购物项的小计
double total = cart.getTotal() - cartMap.get(pid).getSubTotal();
//4.购物车移除当前购物项
cartMap.remove(pid);
Cookie passwordCookie = new Cookie("password","");
usernameCookie.setMaxAge(0);
passwordCookie.setMaxAge(0);
response.addCookie(usernameCookie);
response.addCookie(passwordCookie);
response.sendRedirect(request.getContextPath()+"/product?method=index");
// request.getRequestDispatcher("login.jsp").forward(request,response);
}
}
/**
* 订单的控制层
*/
@WebServlet(urlPatterns = "/order")
public class OrderServlet extends BaseServlet {
private OrderService service = new OrderService();
//提交订单
public void submitOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//大前提 当前必须是登录状态
HttpSession session = request.getSession();
@WebServlet(urlPatterns = "/user")
public class UserServlet extends BaseServlet {
private UserService service = new UserService();
//注册
public void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获得页面表单中的数据
Map<String, String[]> map = request.getParameterMap();
//封装User对象
User user = new User();
//时间转换器:将String-->Date
ConvertUtils.register(new Converter() {
@Override
public Object convert(Class type, Object o) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = sdf.parse(o.toString());
} catch (ParseException e) {
e.printStackTrace();
}
return date;
@WebServlet(urlPatterns = "/product")
public class ProductServlet extends BaseServlet {
private ProductService service = new ProductService();
private CategoryService categoryService = new CategoryService();
//首页展示
public void index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//热门商品
List<Product> productsHot = service.viewHot();
request.setAttribute("productsHot",productsHot);
//跳转至index.jsp
request.getRequestDispatcher("index.jsp").forward(request,response);
}
//查看商品列表
public void viewProductListByCid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//从请求参数中获取当前页
String page = request.getParameter("pageNow");
int pageNow = 1; //默认查询第一页
if(page!=null){
pageNow = Integer.parseInt(page);
}
//从请求参数中获取查询条件 pname cid
public void regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获得页面表单中的数据
Map<String, String[]> map = request.getParameterMap();
//封装User对象
User user = new User();
//时间转换器:将String-->Date
ConvertUtils.register(new Converter() {
@Override
public Object convert(Class type, Object o) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = sdf.parse(o.toString());
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}, Date.class);
try {
//给user对象依次赋值属性
BeanUtils.populate(user,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//uid 用户编号
String uid = CommonUtils.getUUID().replaceAll("-","");
user.setUid(uid);
//code 激活码
String code = CommonUtils.getUUID().replaceAll("-","");
user.setCode(code);
//将密码加密存储
user.setPassword(MD5Utils.md5(user.getPassword()));
//执行service中的注册逻辑
product.setCategory(new Category(cid, cname));
//图片处理
Part file = request.getPart("file");
if (file != null) {
String oldName = file.getHeader("content-disposition");
if (oldName != null && oldName.indexOf(".") > 0) {
String newName = UUID.randomUUID() + oldName.substring(oldName.lastIndexOf("."), oldName.length() - 1);
product.setPimage("img/product/" + newName);
file.write(imageUploadPath + newName);
}
}
String currentImg = product.getPimage();
if (currentImg == null) { //未上传
List<Map<String, Object>> mapList = service.findOneById("product", product.getPid());
String img = null;
for (Map<String, Object> map : mapList) {
img = (String) map.get("pimage");
}
//System.out.println("img = "+img);
if (img != null) {
product.setPimage(img); //设置未原图片
}
}
service.update(product);
response.sendRedirect(request.getContextPath() + "/admin?method=findAll&code=product");
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
//商品导出
public void download(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//表格表头信息
String[] title = {"商品编号", "商品名称", "商品描述", "商品价格", "商品图片", "商品日期"};
String[] prop = {"pid", "pname", "pdesc", "shop_price", "pimage", "pdate"};
//excel的名字
String fileName = "goods.xls";
//sheet页的名字
String sheetName = "商品详情";
//当前页码
int pageNow = Integer.parseInt(request.getParameter("pageNow"));
//数据
List<Product> goods = service.findAll("product", "", pageNow).getList();
HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, prop, goods, null);
//输出文件
response.setContentType("application/octet-stream;charset=utf-8");