Java如何实现玩具商城的前台与后台
短信预约 -IT技能 免费直播动态提醒
这篇文章将为大家详细讲解有关Java如何实现玩具商城的前台与后台,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
一、项目简述
本系统主要实现的功能有:
网上商城系统,前台+后台管理,用户注册,登录,商品展示,分组展示,搜索,收货地址管理,购物车管理,添加,购买,个人信息修改。订单查询等等,后台商品管理,分类管理,库存管理,订单管理,用户管理,信息修改等等。
二、项目运行
环境配置:
Jdk1.8 + Tomcat8.5 + mysql + Eclispe(IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持)
项目技术:
Springboot+ SpringMVC + MyBatis + Jsp + Html+ JavaScript + JQuery + Ajax + maven等等
后台管理代码:
@Controllerpublic class IndexController { @GetMapping("/") public String index(){ return "/index"; } @GetMapping("/contacts") public String contacts(){ return "/common/contacts"; } @GetMapping("/about") public String about(){ return "/common/about"; } @GetMapping("/admin/index") public String adminindex(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException { String admin = (String) session.getAttribute("admin"); if (StringUtils.isEmpty(admin)){ response.sendRedirect(request.getContextPath() + "/");//重定向 } return "/admin/index"; } @GetMapping("/login") public String login(){ return "/user/logreg"; } @GetMapping("/forget") public String forget(){ return "user/forget"; } @GetMapping("/user/center") public String usercenter(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException { String userid = (String) session.getAttribute("userid"); if (StringUtils.isEmpty(userid)){ response.sendRedirect(request.getContextPath() + "/");//重定向 } return "/user/user-center"; } @RequiresPermissions("user:userinfo") @GetMapping("/user/pass") public String userinfo(){ return "/user/updatepass"; } @RequiresPermissions("user:userinfo") @GetMapping("/user/phone") public String userphone(){ return "/user/updatephone"; } @GetMapping("/user/product") public String userproduct(){ return "/user/product/productlist"; } @GetMapping("/user/message") public String commonmessage(){ return "/user/message/message"; } @GetMapping("/user/alertmessage") public String alertmessage(){ return "/user/message/alertmessage"; } @GetMapping("/product-listing") public String toproductlisting() { return "/common/product-listing"; } @GetMapping("/product-search") public String toProductSearchs(String keys, ModelMap modelMap) { if(keys==null){ return "/error/404"; } modelMap.put("keys",keys); return "/common/product-search"; } @GetMapping("/home/console") public String homeconsole(){ return "/admin/home/console"; } @GetMapping("/echars/console") public String echars(){ return "/admin/echars/console"; } @GetMapping("/app/message/index") public String appmessageindex(){ return "/admin/app/message/index"; } @GetMapping("/user/collect") public String usercollect(){ return "/user/collect/collectlist"; } @GetMapping("/user/sold") public String sold(){ return "/user/sold/soldrecord"; } @GetMapping("/admin/sold") public String adminSold(){ return "/admin/sold/soldrecord"; } @GetMapping("/user/newslist") public String userNews(){ return "/common/listnews"; } @GetMapping("/admin/newslist") public String adminNews(){ return "/admin/news/newslist"; }}
订单和商品服务类:
@WebServlet("/backstage_goodsServlet")public class GoodsServlet extends HttpServlet{GoodsService service = new GoodsService();@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String action = req.getParameter("action");switch(action) {case "addGoods":addGoods(req,resp);break;case "getGoodsList":getGoodsList(req,resp);break;case "getGoodsListByName":getGoodsListByName(req,resp);break;case "deleteGoods":deleteGoods(req,resp);break;case "toGoodsUpdatePage":toGoodsUpdatePage(req,resp);break;case "updateGoods":updateGoods(req,resp);break;case "upGoodsImage":upGoodsImage(req,resp);break;case "fastbuy":sendOrder(req,resp);break;}}public void sendOrder(HttpServletRequest req, HttpServletResponse resp) throws IOException {//设置请求编码格式:req.setCharacterEncoding("utf-8");//设置响应编码格式resp.setContentType("text/html;charset=utf-8");SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式Orders order = new Orders();order.setNumber(order.getRandomString(10));order.setTime(df.format(new Date()));order.setName(req.getParameter("recipients"));order.setAddress(req.getParameter("address"));order.setPhone(req.getParameter("phone"));order.setAddress_label(req.getParameter("addressLabel"));order.setSex(req.getParameter("sex"));order.setUser("sjb");order.setGoods_id(99);order.setGoods_num(3);order.setGoods_status(1);int d = service.addOrder(order);try {if(d>0) {JSONResult ok = JSONResult.ok();resp.getWriter().println(JsonUtil.javaObjectToJson(ok));}else {JSONResult error = JSONResult.errorMsg("订单提交失败!");resp.getWriter().println(JsonUtil.javaObjectToJson(error));}} catch (Exception e) {e.printStackTrace();}} public void addGoods(HttpServletRequest req,HttpServletResponse resp) throws IOException {//设置请求编码格式:req.setCharacterEncoding("utf-8");//设置响应编码格式resp.setContentType("text/html;charset=utf-8");FileUploadUtil upFile = new FileUploadUtil();ServletContext servletContext = req.getSession().getServletContext();List<FileItem> items= upFile.getRequsetFileItems(req,servletContext);//保存所有用户提交的 表单数据 的mapMap<String, String> formData = new HashMap<>();String savePath = new File(getServletContext().getRealPath("/")).getParentFile().getParentFile().getPath()+"/imgs";try {//遍历for (FileItem file : items) {if(!file.isFormField()) {String fileSuffix = FileUploadUtil.getFileSuffix(file).toUpperCase();//必须是jpg或png 图片文件才能进行上传操作if("JPG".equals(fileSuffix) || "PNG".equals(fileSuffix)) {//生成新图片名String imgName = FileUploadUtil.getImgNewName(fileSuffix);FileUploadUtil.saveFile(file, savePath, imgName);formData.put("imgUrl",imgName);}}else {//非文件数据存入formData.put(file.getFieldName(), file.getString("utf-8"));}}} catch (UnsupportedEncodingException e) {e.printStackTrace();}Goods goods = new Goods();goods.setName(formData.get("goodsName"));goods.setNum(Integer.parseInt(formData.get("num")));goods.setPrice(Double.parseDouble(formData.get("price")));goods.setImgurl(formData.get("imgUrl"));goods.setType(formData.get("type"));goods.setDescription(formData.get("description"));goods.setColor(formData.get("color"));goods.setMemory(formData.get("memory"));goods.setCreateDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));int d = service.addGoods(goods);try {if(d>0) {JSONResult ok = JSONResult.ok();resp.getWriter().println(JsonUtil.javaObjectToJson(ok));}else {JSONResult errorMsg = JSONResult.errorMsg("添加失败,请重试");resp.getWriter().println(JsonUtil.javaObjectToJson(errorMsg));}} catch (Exception e) {e.printStackTrace();}}public void getGoodsList(HttpServletRequest req,HttpServletResponse resp) {List<Goods> allGoods = service.getAllGoods();req.setAttribute("goodsList", allGoods);try {req.getRequestDispatcher("/backstage/tgls/goodsManage/goods_list.jsp").forward(req, resp);} catch (ServletException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}public void getGoodsListByName(HttpServletRequest req,HttpServletResponse resp) throws IOException {//设置请求编码格式:req.setCharacterEncoding("utf-8");//设置响应编码格式resp.setContentType("text/html;charset=utf-8");String name = req.getParameter("goodsName");String type = req.getParameter("type");Map<String,String> parmas = new HashMap<>();parmas.put("name", name);parmas.put("type", type);List<Goods> list = service.getGoodsByName(parmas);try {if(list != null) {JSONResult ok = JSONResult.ok(list);resp.getWriter().println(JsonUtil.javaObjectToJson(ok));}else {JSONResult errorMsg = JSONResult.errorMsg("未获取到任何数据,请重试");resp.getWriter().println(JsonUtil.javaObjectToJson(errorMsg));}} catch (Exception e) {e.printStackTrace();}}public void toGoodsUpdatePage(HttpServletRequest req,HttpServletResponse resp) {int id = Integer.parseInt(req.getParameter("id"));Goods goods = service.getGoodsInfoById(id);req.setAttribute("goods", goods);try {req.getRequestDispatcher("/backstage/tgls/goodsManage/goods_update.jsp").forward(req, resp);} catch (ServletException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}public void upGoodsImage(HttpServletRequest req,HttpServletResponse resp) throws IOException {//设置请求编码格式:req.setCharacterEncoding("utf-8");//设置响应编码格式resp.setContentType("text/html;charset=utf-8");FileUploadUtil upFile = new FileUploadUtil();ServletContext servletContext = req.getSession().getServletContext();List<FileItem> items= upFile.getRequsetFileItems(req,servletContext);String savePath = new File(getServletContext().getRealPath("/")).getParentFile().getParentFile().getPath()+"/imgs";String imgName = null;try {//遍历for (FileItem file : items) {if(!file.isFormField()) {String fileSuffix = FileUploadUtil.getFileSuffix(file);//必须是jpg或png 图片文件才能进行上传操作if("jpg".equals(fileSuffix) || "png".equals(fileSuffix)) {//生成新图片名imgName = FileUploadUtil.getImgNewName(fileSuffix);FileUploadUtil.saveFile(file, savePath, imgName);}}}int d = service.updateGoodsImgById(imgName, Integer.parseInt(req.getParameter("id")));if(d>0) {JSONResult ok = JSONResult.ok(imgName);resp.getWriter().println(JsonUtil.javaObjectToJson(ok));}else {JSONResult errorMsg = JSONResult.errorMsg("修改失败,请重试");resp.getWriter().println(JsonUtil.javaObjectToJson(errorMsg));}} catch (Exception e) {e.printStackTrace();}}public void updateGoods(HttpServletRequest req,HttpServletResponse resp) throws IOException {//设置请求编码格式:req.setCharacterEncoding("utf-8");//设置响应编码格式resp.setContentType("text/html;charset=utf-8");Goods goods = new Goods();goods.setId(Integer.parseInt(req.getParameter("id")));goods.setName(req.getParameter("goodsName"));goods.setNum(Integer.parseInt(req.getParameter("num")));goods.setPrice(Double.parseDouble(req.getParameter("price")));goods.setType(req.getParameter("type"));goods.setColor(req.getParameter("color"));goods.setMemory(req.getParameter("memory"));goods.setDescription(req.getParameter("description"));int d = service.updateGoodsById(goods);try {if(d>0) {JSONResult ok = JSONResult.ok();resp.getWriter().println(JsonUtil.javaObjectToJson(ok));}else {JSONResult errorMsg = JSONResult.errorMsg("修改失败,请重试");resp.getWriter().println(JsonUtil.javaObjectToJson(errorMsg));}} catch (Exception e) {e.printStackTrace();}} public void deleteGoods(HttpServletRequest req,HttpServletResponse resp) throws IOException {//设置请求编码格式:req.setCharacterEncoding("utf-8");//设置响应编码格式resp.setContentType("text/html;charset=utf-8");int id = Integer.parseInt(req.getParameter("id"));int d = service.deleteGoodsById(id);try {if(d>0) {JSONResult ok = JSONResult.ok();resp.getWriter().println(JsonUtil.javaObjectToJson(ok));}else {JSONResult errorMsg = JSONResult.errorMsg("删除失败,请重试");resp.getWriter().println(JsonUtil.javaObjectToJson(errorMsg));}} catch (Exception e) {e.printStackTrace();}}}
订单服务类:
@WebServlet("/backstage_ordersServlet")public class OrdersServlet extends HttpServlet{OrdersService service = new OrdersService();@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String action = req.getParameter("action");System.out.println(action);switch(action) {case "getOrdersList":getOrdersList(req,resp);break;case "getOrdersListByName":getOrdersListByName(req,resp);break;case "deleteOrders":deleteOrders(req,resp);break;case "deleteAllOrders":deleteAllOrders(req,resp);break;case "toOrdersUpdatePage":toOrdersUpdatePage(req,resp);break;case "updateOrders":updateOrders(req,resp);break;case "fastbuy":sendOrder(req,resp);break;}} private void deleteAllOrders(HttpServletRequest req, HttpServletResponse resp) throws IOException {//设置请求编码格式:req.setCharacterEncoding("utf-8");//设置响应编码格式resp.setContentType("text/html;charset=utf-8");// TODO 自动生成的方法存根int d = service.deleteAllOrders();try {if(d>0) {JSONResult ok = JSONResult.ok();resp.getWriter().println(JsonUtil.javaObjectToJson(ok));}else {JSONResult errorMsg = JSONResult.errorMsg("删除失败,请重试");resp.getWriter().println(JsonUtil.javaObjectToJson(errorMsg));}} catch (Exception e) {e.printStackTrace();}} public void sendOrder(HttpServletRequest req, HttpServletResponse resp) throws IOException {//设置请求编码格式:req.setCharacterEncoding("utf-8");//设置响应编码格式resp.setContentType("text/html;charset=utf-8");SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式User user =(User) req.getSession().getAttribute("user");Orders order = new Orders();order.setNumber(order.getRandomString(10));order.setTime(df.format(new Date()));order.setName(req.getParameter("recipients"));order.setAddress(req.getParameter("address"));order.setPhone(req.getParameter("phone"));order.setAddress_label(req.getParameter("addressLabel"));order.setSex(req.getParameter("sex"));order.setUser(user.getUserName());order.setGoods_id(Integer.parseInt(req.getParameter("id")));order.setGoods_num(Integer.parseInt(req.getParameter("num")));order.setGoods_status(1);int d = service.addOrder(order);try {if(d>0) {JSONResult ok = JSONResult.ok();resp.getWriter().println(JsonUtil.javaObjectToJson(ok));}else {JSONResult error = JSONResult.errorMsg("订单提交失败!");resp.getWriter().println(JsonUtil.javaObjectToJson(error));}} catch (Exception e) {e.printStackTrace();}} public void getOrdersList(HttpServletRequest req,HttpServletResponse resp) {List<Orders> allOrders = service.getAllOrders();req.setAttribute("ordersList",allOrders);try {req.getRequestDispatcher("/backstage/tgls/ordersManage/orders_list.jsp").forward(req, resp);} catch (ServletException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}public void getOrdersListByName(HttpServletRequest req,HttpServletResponse resp) throws IOException {//设置请求编码格式:req.setCharacterEncoding("utf-8");//设置响应编码格式resp.setContentType("text/html;charset=utf-8");String name = req.getParameter("OrdersUser");//String type = req.getParameter("type");Map<String,String> parmas = new HashMap<>();parmas.put("name", name);//parmas.put("type", type);List<Orders> list = service.getOrdersByName(parmas);try {if(list != null) {JSONResult ok = JSONResult.ok(list);resp.getWriter().println(JsonUtil.javaObjectToJson(ok));}else {JSONResult errorMsg = JSONResult.errorMsg("未获取到任何数据,请重试");resp.getWriter().println(JsonUtil.javaObjectToJson(errorMsg));}} catch (Exception e) {e.printStackTrace();}}public void toOrdersUpdatePage(HttpServletRequest req,HttpServletResponse resp) {int id = Integer.parseInt(req.getParameter("id"));Orders orders = service.getOrdersInfoById(id);req.setAttribute("orders", orders);try {req.getRequestDispatcher("/backstage/tgls/ordersManage/orders_update.jsp").forward(req, resp);} catch (ServletException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}public void updateOrders(HttpServletRequest req,HttpServletResponse resp) throws IOException {//设置请求编码格式:req.setCharacterEncoding("utf-8");//设置响应编码格式resp.setContentType("text/html;charset=utf-8");Orders orders = new Orders();orders.setId(Integer.parseInt(req.getParameter("id")));orders.setNumber(req.getParameter("number"));orders.setUser(req.getParameter("user"));orders.setTime(req.getParameter("time"));orders.setName(req.getParameter("name"));orders.setSex(req.getParameter("sex"));orders.setAddress(req.getParameter("address"));orders.setPhone(req.getParameter("phone"));orders.setAddress_label(req.getParameter("address_label"));orders.setGoods_id(Integer.parseInt(req.getParameter("goods_id")));orders.setGoods_num(Integer.parseInt(req.getParameter("goods_num")));orders.setGoods_status(Integer.parseInt(req.getParameter("goods_status")));System.out.println(orders);int d = service.updateOrdersById(orders);System.out.println(d);try {if(d>0) {JSONResult ok = JSONResult.ok();resp.getWriter().println(JsonUtil.javaObjectToJson(ok));}else {JSONResult errorMsg = JSONResult.errorMsg("修改失败,请重试");resp.getWriter().println(JsonUtil.javaObjectToJson(errorMsg));}} catch (Exception e) {e.printStackTrace();}} public void deleteOrders(HttpServletRequest req,HttpServletResponse resp) throws UnsupportedEncodingException {//设置请求编码格式:req.setCharacterEncoding("utf-8");//设置响应编码格式resp.setContentType("text/html;charset=utf-8");int id = Integer.parseInt(req.getParameter("id"));int d = service.deleteOrdersById(id);try {if(d>0) {JSONResult ok = JSONResult.ok();resp.getWriter().println(JsonUtil.javaObjectToJson(ok));}else {JSONResult errorMsg = JSONResult.errorMsg("删除失败,请重试");resp.getWriter().println(JsonUtil.javaObjectToJson(errorMsg));}} catch (Exception e) {e.printStackTrace();}}}
用户服务类:
@WebServlet("/backstage_userServlet")public class UserServlet extends HttpServlet{UserService service = new UserService();@Overrideprotected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String action = req.getParameter("action");switch(action) {case "login":login(req, resp);break;case "modifyPassword":modifyPassword(req, resp);break;case "checkOldPassword":checkOldPassword(req, resp);break;case "afterModifyPassword":afterModifyPassword(req, resp);break;case "logout":logout(req, resp);break;}}public void login(HttpServletRequest req, HttpServletResponse resp) throws IOException {//设置请求编码格式:req.setCharacterEncoding("utf-8");//设置响应编码格式resp.setContentType("text/html;charset=utf-8");//获取前端页面传来的用户名String userName = req.getParameter("userName");//获取前端页面传来的密码String password = req.getParameter("password");// 1、先验证该用户的角色是否为管理员String userRole = service.getUserRoleByName(userName);try {if(!"admin".equals(userRole)) {JSONResult errorMsg = JSONResult.errorMsg("暂无登录权限");resp.getWriter().println(JsonUtil.javaObjectToJson(errorMsg));}else {//2、获取用户数据 进行用户名和密码验证User user = service.getUserByNameAndPassword(userName, password);if(user!=null) {//将用户数据保存到session 作用域中,方便在后续的操作中使用用户数据req.getSession().setAttribute("user", user);JSONResult ok = JSONResult.ok();resp.getWriter().println(JsonUtil.javaObjectToJson(ok));}else {// 将错误信息封装在结果集中JSONResult result = JSONResult.errorMsg("用户名或密码错误,请重试");//以json的形式返回给前端resp.getWriter().println(JsonUtil.javaObjectToJson(result));}}} catch (Exception e) {e.printStackTrace();}}public void checkOldPassword(HttpServletRequest req, HttpServletResponse resp) throws IOException {//设置请求编码格式:req.setCharacterEncoding("utf-8");//设置响应编码格式resp.setContentType("text/html;charset=utf-8");User user =(User) req.getSession().getAttribute("user");String oldPassword = service.getPasswordById(user.getId()); String password = req.getParameter("password");try {if(!oldPassword.equals(password)) {JSONResult errorMsg = JSONResult.errorMsg("原始密码错误,请重新输入");resp.getWriter().println(JsonUtil.javaObjectToJson(errorMsg));}else {JSONResult ok = JSONResult.ok();resp.getWriter().println(JsonUtil.javaObjectToJson(ok));}} catch (IOException e) {e.printStackTrace();}}public void modifyPassword(HttpServletRequest req, HttpServletResponse resp) throws IOException {//设置请求编码格式:req.setCharacterEncoding("utf-8");//设置响应编码格式resp.setContentType("text/html;charset=utf-8");String password = req.getParameter("newPassword");User user =(User) req.getSession().getAttribute("user");int id = user.getId();int d = service.updatePasswordById(id, password);try {if(d>0) {JSONResult ok = JSONResult.ok();resp.getWriter().println(JsonUtil.javaObjectToJson(ok));}else {JSONResult errorMsg = JSONResult.errorMsg("修改失败,请重试");resp.getWriter().println(JsonUtil.javaObjectToJson(errorMsg));}} catch (Exception e) {e.printStackTrace();}} public void afterModifyPassword(HttpServletRequest req, HttpServletResponse resp) { req.getSession().removeAttribute("user");try {//使用iframe时,要避免这种直接跳转的方式// 此时只会让内嵌的iframe跳转到登录页,并非整个页面//resp.sendRedirect("backstage/login.jsp");PrintWriter writer = resp.getWriter();writer.print("<html>");writer.print("<script>");writer.print("window.open('"+ req.getContextPath()+"/backstage/login.jsp','_top')");writer.print("</script>");writer.print("</html>");} catch (IOException e) {e.printStackTrace();} } public void logout(HttpServletRequest req, HttpServletResponse resp) {req.getSession().removeAttribute("user");try {resp.sendRedirect("backstage/login.jsp");} catch (IOException e) {e.printStackTrace();}}}
关于“Java如何实现玩具商城的前台与后台”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341