亲宝软件园·资讯

展开

Java 玩具商城

qq_1334611189 人气:0

一、项目简述

本系统主要实现的功能有:
网上商城系统,前台+后台管理,用户注册,登录,商品展示,分组展示,搜索,收货地址管理,购物车管理,添加,购买,个人信息修改。订单查询等等,后台商品管理,分类管理,库存管理,订单管理,用户管理,信息修改等等。

二、项目运行

环境配置:

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();
		}
	}
}

加载全部内容

相关教程
猜你喜欢
用户评论