Java實戰玩具商城的前臺與後臺實現流程

一、項目簡述

本系統主要實現的功能有:
網上商城系統,前臺+後臺管理,用戶註冊,登錄,商品展示,分組展示,搜索,收貨地址管理,購物車管理,添加,購買,個人信息修改。訂單查詢等等,後臺商品管理,分類管理,庫存管理,訂單管理,用戶管理,信息修改等等。

二、項目運行

環境配置:

Jdk1.8 + Tomcat8.5 + mysql + Eclispe(IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持)

項目技術:

Springboot+ SpringMVC + MyBatis + Jsp + Html+ JavaScript + JQuery + Ajax + maven等等

後臺管理代碼:

@Controller
public 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();
	
	@Override
	protected 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;
		}
	}
	
	/**
	 * 提交訂單
	 * @throws IOException 
	 */
	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();
		}
	}
 
	/**
	 * 保存商品
	 * @throws IOException 
	 */
	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);
		
		//保存所有用戶提交的 表單數據 的map
		Map<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();
		}	
	}
	
	
	/**
	 * @throws IOException 
	 * 根據商品名查詢商品
	 * @param req
	 * @param resp
	 * @throws  
	 */
	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();
		}	
		
	}
	
	
	
	/**
	 *修改商品信息時,如果有修改圖片,先將圖片進行修改
	 * @throws IOException 
	 */
	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();
		}	
	}
	
	
	
	/**
	 *  修改商品
	 * @throws IOException 
	 */
	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();
		}
	}
	
	
 
	/**
	 * 刪除商品
	 * @throws IOException 
	 */
	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();
	
	@Override
	protected 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();
		}
	}
 
	/**
	 * 提交訂單
	 * @throws IOException 
	 */
	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();
		}	
	}
	
	
	/**
	 * 根據訂單名查詢商品(註意!類別沒改)
	 * @param req
	 * @param resp
	 * @throws IOException 
	 */
	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();
		}	
		
	}
	
	/**
	 *  修改訂單
	 * @throws IOException 
	 */
	
	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();
		}
	}
	
	
 
	/**
	 * 刪除訂單
	 * @throws UnsupportedEncodingException 
	 */
	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();
	
	@Override
	protected 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;
		}
	}
	
	/**
	 * 用戶登錄
	 * @throws IOException 
	 */
	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();
		}
	}
	
	/**
	 * 檢查舊密碼是否正確 ,在修改密碼操作時使用
	 * @throws IOException 
	 */
	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();
		}
		
	}
	
	
	/**
	 *  修改密碼
	 * @throws IOException 
	 */
	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();
		}
	}
	
	/**
	 * 成功修改密碼後,清除session中的數據,並且重新跳轉到登錄頁
	 * @param req
	 * @param resp
	 */
    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實戰玩具商城的前臺與後臺實現流程的文章就介紹到這瞭,更多相關Java 玩具商城內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: