源码获取:俺的博客首页 "资源" 里下载!
项目介绍
本项目分为前后台,分为管理员与普通用户两种角色,管理员登录后台,普通用户登录前台;
管理员登录包含以下功能:
管理员登录,修改管理员信息,订单管理,客户管理,水产管理,类目管理等功能。
用户角色包含以下功能:
查看首页,用户登录,修改个人信息,按分类查看水产,查看热销水产,查看新水产,查看商品详情,查看我的购物车,提交订单,查看我的订单等功能。
环境需要
1.运行环境:最好是java jdk 1.8,我们在这个平台上运行的。其他版本理论上也可以。
2.IDE环境:IDEA,Eclipse,Myeclipse都可以。推荐IDEA;
3.tomcat环境:Tomcat 7.x,8.x,9.x版本均可
4.硬件环境:windows 7/8/10 1G内存以上;或者 Mac OS;
5.数据库:MySql 5.7版本;
6.是否Maven项目:否;
技术栈
JSP+CSS+jQuery+bootstrap+mysql+servlet
使用说明
1. 使用Navicat或者其它工具,在mysql中创建对应名称的数据库,并导入项目的sql文件;
2. 使用IDEA/Eclipse/MyEclipse导入项目,Eclipse/MyEclipse导入时,若为maven项目请选择maven;
若为maven项目,导入成功后请执行maven clean;maven install命令,然后运行;
3. 将项目中src/utils/DBUtil.java配置文件中的数据库配置改为自己的配置;
4. 运行项目,输入localhost:8080/jsp_scp_shop/ 登录 注:tomcat中配置项目路径必须为jsp_scp_shop,否则会有异常;
用户账号/密码:user/123456
管理员账号/密码:admin/admin
用户管理控制层:
@Controller@RequestMapping("/user")public class UserController extends BaseController {/*** 依赖注入 start dao/service/===*/@Autowiredprivate UserService userService;// --------------------------------------- 华丽分割线 ------------------------------/*********************************查询列表【不分页】***********************************************//*** 【不分页 => 查询列表 => 无条件】* @Title: listAll * @Description: TODO(这里用一句话描述这个方法的作用) * @param @return 设定文件 * @author* @return String 返回类型 * @throws*/@RequestMapping(value = "/listAll")public String listAll(User user, Model model, HttpServletRequest request, HttpServletResponse response){List<User> listAll = userService.listAll();model.addAttribute("list", listAll);return "user/user";}/*** 【不分页=》查询列表=>有条件】* @Title: listByEntity * @Description: TODO(这里用一句话描述这个方法的作用) * @param @return 设定文件 * @author* @return String 返回类型 * @throws*/@RequestMapping(value = "/listByEntity")public String listByEntity(User user, Model model, HttpServletRequest request, HttpServletResponse response){List<User> listAll = userService.listAllByEntity(user);model.addAttribute("list", listAll);return "user/user";}/*** 【不分页=》查询列表=>有条件】* @Title: listByMap * @Description: TODO(这里用一句话描述这个方法的作用) * @param @return 设定文件 * @author * @return String 返回类型 * @throws*/@RequestMapping(value = "/listByMap")public String listByMap(User user, Model model, HttpServletRequest request, HttpServletResponse response){//通过map查询Map<String,Object> params = new HashMap<String,Object>();if(!isEmpty(user.getUserName())){params.put("userName", user.getUserName());}if(!isEmpty(user.getPassWord())){params.put("passWord", user.getPassWord());}if(!isEmpty(user.getPhone())){params.put("phone", user.getPhone());}if(!isEmpty(user.getRealName())){params.put("realName", user.getRealName());}if(!isEmpty(user.getSex())){params.put("sex", user.getSex());}if(!isEmpty(user.getAddress())){params.put("address", user.getAddress());}if(!isEmpty(user.getEmail())){params.put("email", user.getEmail());}List<User> listAll = userService.listByMap(params);model.addAttribute("list", listAll);return "user/user";}/*********************************查询列表【分页】***********************************************//*** 分页查询 返回list对象(通过对象)* * @param request* @param response* @return*/@RequestMapping(value = "/findByObj")public String findByObj(User user, Model model, HttpServletRequest request, HttpServletResponse response) {//分页查询Pager<User> pagers = userService.findByEntity(user);model.addAttribute("pagers", pagers);//存储查询条件model.addAttribute("obj", user);return "user/user";}/*** 分页查询 返回list对象(通过对By Sql)* * @param request* @param response* @return*/@RequestMapping(value = "/findBySql")public String findBySql(User user, Model model, HttpServletRequest request, HttpServletResponse response) {//分页查询String sql = "SELECT * FROM user WHERE 1=1 ";if(!isEmpty(user.getUserName())){sql += " and userName like '%"+user.getUserName()+"%'";}if(!isEmpty(user.getPassWord())){sql += " and passWord like '%"+user.getPassWord()+"%'";}if(!isEmpty(user.getPhone())){sql += " and phone like '%"+user.getPhone()+"%'";}if(!isEmpty(user.getRealName())){sql += " and realName like '%"+user.getRealName()+"%'";}if(!isEmpty(user.getSex())){sql += " and sex like '%"+user.getSex()+"%'";}if(!isEmpty(user.getAddress())){sql += " and address like '%"+user.getAddress()+"%'";}if(!isEmpty(user.getEmail())){sql += " and email like '%"+user.getEmail()+"%'";}sql += " ORDER BY ID DESC ";Pager<User> pagers = userService.findBySqlRerturnEntity(sql);model.addAttribute("pagers", pagers);//存储查询条件model.addAttribute("obj", user);return "user/user";}/*** 分页查询 返回list对象(通过Map)* * @param request* @param response* @return*/@RequestMapping(value = "/findByMap")public String findByMap(User user, Model model, HttpServletRequest request, HttpServletResponse response) {//通过map查询Map<String,Object> params = new HashMap<String,Object>();if(!isEmpty(user.getUserName())){params.put("userName", user.getUserName());}if(!isEmpty(user.getPassWord())){params.put("passWord", user.getPassWord());}if(!isEmpty(user.getPhone())){params.put("phone", user.getPhone());}if(!isEmpty(user.getRealName())){params.put("realName", user.getRealName());}if(!isEmpty(user.getSex())){params.put("sex", user.getSex());}if(!isEmpty(user.getAddress())){params.put("address", user.getAddress());}if(!isEmpty(user.getEmail())){params.put("email", user.getEmail());}//分页查询Pager<User> pagers = userService.findByMap(params);model.addAttribute("pagers", pagers);//存储查询条件model.addAttribute("obj", user);return "user/user";}/**********************************【增删改】******************************************************//*** 跳至添加页面* @return*/@RequestMapping(value = "/add")public String add() {return "user/add";}/*** 跳至详情页面* @return*/@RequestMapping(value = "/view")public String view(Model model,HttpServletRequest request) {Object attribute = request.getSession().getAttribute("userId");if (attribute == null){return "redirect:/login/uLogin";}JSONObject js = new JSONObject();Integer userId = Integer.valueOf(attribute.toString());User obj = userService.load(userId);model.addAttribute("obj",obj);return "user/view";}/*** 添加执行* @return*/@RequestMapping(value = "/exAdd")public String exAdd(User user, Model model, HttpServletRequest request, HttpServletResponse response) {userService.insert(user);return "redirect:/user/findBySql.action";}/*** 跳至修改页面* @return*/@RequestMapping(value = "/update")public String update(Integer id,Model model) {User obj = userService.load(id);model.addAttribute("obj",obj);return "user/update";}/*** 添加修改* @return*/@RequestMapping(value = "/exUpdate")public String exUpdate(User user, Model model, HttpServletRequest request, HttpServletResponse response) {//1.通过实体类修改,可以多传修改条件Object attribute = request.getSession().getAttribute("userId");if (attribute == null){return "redirect:/login/uLogin";}JSONObject js = new JSONObject();user.setId(Integer.valueOf(attribute.toString()));userService.updateById(user);//2.通过主键id修改//userService.updateById(user);return "redirect:/user/view.action";}/*** 删除通过主键* @return*/@RequestMapping(value = "/delete")public String delete(Integer id, Model model, HttpServletRequest request, HttpServletResponse response) {///1.通过主键删除userService.deleteById(id);/*以下是多种删除方式*/////2.通过实体条件删除//userService.deleteByEntity(user);////3.通过参数删除////通过map查询//Map<String,Object> params = new HashMap<String,Object>();//// if(!isEmpty(user.getUserName())){// params.put("userName", user.getUserName());//}// // if(!isEmpty(user.getPassWord())){// params.put("passWord", user.getPassWord());//}// // if(!isEmpty(user.getPhone())){// params.put("phone", user.getPhone());//}// // if(!isEmpty(user.getRealName())){// params.put("realName", user.getRealName());//}// // if(!isEmpty(user.getSex())){// params.put("sex", user.getSex());//}// // if(!isEmpty(user.getAddress())){// params.put("address", user.getAddress());//}// // if(!isEmpty(user.getEmail())){// params.put("email", user.getEmail());//}// //userService.deleteByMap(params);////4.状态删除//User load = userService.getById(user.getId())//load.setIsDelete(1);//userService.update(load);//5.状态删除//User load = userService.load(id);//load.setIsDelete(1);//userService.update(load);return "redirect:/user/findBySql.action";}// --------------------------------------- 华丽分割线 ------------------------------// --------------------------------------- 【下面是ajax操作的方法。】 ------------------------------/*********************************查询列表【不分页】***********************************************//*** 【不分页 => 查询列表 => 无条件】* @Title: listAll * @Description: TODO(这里用一句话描述这个方法的作用) * @param @return 设定文件 * @author* @return String 返回类型 * @throws*/@RequestMapping(value = "/listAllJson", method = RequestMethod.POST)@ResponseBodypublic String listAllJson(User user, HttpServletRequest request, HttpServletResponse response){List<User> listAll = userService.listAll();JSONObject jsonObject = new JSONObject();jsonObject.put("list", listAll);jsonObject.put("obj", user);return jsonObject.toString();}/*** 【不分页=》查询列表=>有条件】* @Title: listByEntity * @Description: TODO(这里用一句话描述这个方法的作用) * @param @return 设定文件 * @author* @return String 返回类型 * @throws*/@RequestMapping(value = "/listByEntityJson", method = RequestMethod.POST)@ResponseBodypublic String listByEntityJson(User user, HttpServletRequest request, HttpServletResponse response){List<User> listAll = userService.listAllByEntity(user);JSONObject jsonObject = new JSONObject();jsonObject.put("list", listAll);jsonObject.put("obj", user);return jsonObject.toString();}/*** 【不分页=》查询列表=>有条件】* @Title: listByMap * @Description: TODO(这里用一句话描述这个方法的作用) * @param @return 设定文件 * @author * @return String 返回类型 * @throws*/@RequestMapping(value = "/listByMapJson", method = RequestMethod.POST)@ResponseBodypublic String listByMapJson(User user,HttpServletRequest request, HttpServletResponse response){//通过map查询Map<String,Object> params = new HashMap<String,Object>();if(!isEmpty(user.getUserName())){params.put("userName", user.getUserName());}if(!isEmpty(user.getPassWord())){params.put("passWord", user.getPassWord());}if(!isEmpty(user.getPhone())){params.put("phone", user.getPhone());}if(!isEmpty(user.getRealName())){params.put("realName", user.getRealName());}if(!isEmpty(user.getSex())){params.put("sex", user.getSex());}if(!isEmpty(user.getAddress())){params.put("address", user.getAddress());}if(!isEmpty(user.getEmail())){params.put("email", user.getEmail());}List<User> listAll = userService.listByMap(params);JSONObject jsonObject = new JSONObject();jsonObject.put("list", listAll);jsonObject.put("obj", user);return jsonObject.toString();}/*** 分页查询 返回list json(通过对象)* * @param request* @param response* @return*/@RequestMapping(value = "/findByObjJson", method = RequestMethod.POST)@ResponseBodypublic String findByObjByEntityJson(User user, HttpServletRequest request, HttpServletResponse response) {//分页查询Pager<User> pagers = userService.findByEntity(user);JSONObject jsonObject = new JSONObject();jsonObject.put("pagers", pagers);jsonObject.put("obj", user);return jsonObject.toString();}/*** 分页查询 返回list json(通过Map)* * @param request* @param response* @return*/@RequestMapping(value = "/findByMapJson", method = RequestMethod.POST)@ResponseBodypublic String findByMapJson(User user,HttpServletRequest request, HttpServletResponse response) {//通过map查询Map<String,Object> params = new HashMap<String,Object>();if(!isEmpty(user.getUserName())){params.put("userName", user.getUserName());}if(!isEmpty(user.getPassWord())){params.put("passWord", user.getPassWord());}if(!isEmpty(user.getPhone())){params.put("phone", user.getPhone());}if(!isEmpty(user.getRealName())){params.put("realName", user.getRealName());}if(!isEmpty(user.getSex())){params.put("sex", user.getSex());}if(!isEmpty(user.getAddress())){params.put("address", user.getAddress());}if(!isEmpty(user.getEmail())){params.put("email", user.getEmail());}//分页查询Pager<User> pagers = userService.findByMap(params);JSONObject jsonObject = new JSONObject();jsonObject.put("pagers", pagers);jsonObject.put("obj", user);return jsonObject.toString();}/*** ajax 添加* @param * @return*/@RequestMapping(value = "/exAddJson", method = RequestMethod.POST)@ResponseBodypublic String exAddJson(User user, Model model, HttpServletRequest request, HttpServletResponse response) {userService.insert(user);JSONObject jsonObject = new JSONObject();jsonObject.put("message", "添加成功");return jsonObject.toString();}/*** ajax 修改* @param * @return*/@RequestMapping(value = "/exUpdate.json", method = RequestMethod.POST)@ResponseBodypublic String exUpdateJson(User user, Model model, HttpServletRequest request, HttpServletResponse response) {//1.通过实体类修改,可以多传修改条件userService.updateById(user);//2.通过主键id修改//userService.updateById(user);JSONObject jsonObject = new JSONObject();jsonObject.put("message", "修改成功");return jsonObject.toString();}/*** ajax 删除* @return*/@RequestMapping(value = "/delete.json", method = RequestMethod.POST)@ResponseBodypublic String exDeleteJson(Integer id, Model model, HttpServletRequest request, HttpServletResponse response) {///1.通过主键删除userService.deleteById(id);/*以下是多种删除方式*/////2.通过实体条件删除//userService.deleteByEntity(user);////3.通过参数删除// //通过map查询//Map<String,Object> params = new HashMap<String,Object>();//// if(!isEmpty(user.getUserName())){// params.put("userName", user.getUserName());//}// // if(!isEmpty(user.getPassWord())){// params.put("passWord", user.getPassWord());//}// // if(!isEmpty(user.getPhone())){// params.put("phone", user.getPhone());//}// // if(!isEmpty(user.getRealName())){// params.put("realName", user.getRealName());//}// // if(!isEmpty(user.getSex())){// params.put("sex", user.getSex());//}// // if(!isEmpty(user.getAddress())){// params.put("address", user.getAddress());//}// // if(!isEmpty(user.getEmail())){// params.put("email", user.getEmail());//}// //userService.deleteByMap(params);////4.状态删除//User load = userService.getById(user.getId())//load.setIsDelete(1);//userService.updateById(load);//5.状态删除//User load = userService.load(id);//load.setIsDelete(1);//userService.updateById(load);JSONObject jsonObject = new JSONObject();jsonObject.put("message", "删除成功");return jsonObject.toString();}/*** 单文件上传* @param file* @param request* @param model* @return*/@RequestMapping(value = "/saveFile") public String saveFile(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, Model model) { System.out.println("开始"); String path = request.getSession().getServletContext().getRealPath("/upload"); String fileName = file.getOriginalFilename(); System.out.println(path); File targetFile = new File(path, fileName); if(!targetFile.exists()){ targetFile.mkdirs(); } //保存 try { file.transferTo(targetFile); } catch (Exception e) { e.printStackTrace(); } return ""; } /*** springMvc多文件上传* @param files* @param id* @return*/@RequestMapping(value = "/saveFiles")public String saveFiles(@RequestParam("file") CommonsMultipartFile[] files,Integer id,HttpServletRequest request){for(int i = 0;i<files.length;i++){System.out.println("fileName---------->" + files[i].getOriginalFilename());if(!files[i].isEmpty()){int pre = (int) System.currentTimeMillis();try {//拿到输出流,同时重命名上传的文件String filePath = request.getRealPath("/upload");File f=new File(filePath);if(!f.exists()){f.mkdirs();}String fileNmae=new Date().getTime() + files[i].getOriginalFilename();File file=new File(filePath+"/"+pre + files[i].getOriginalFilename());if(!file.exists()){file.createNewFile();}files[i].transferTo(file);} catch (Exception e) {e.printStackTrace();System.out.println("上传出错");}}}return "";}// --------------------------------------- 华丽分割线 ------------------------------}
购物车管理控制层:
@Controller@RequestMapping("/car")public class CarController extends BaseController {@Autowiredprivate ItemService itemService;@Autowiredprivate AddressService addressService;/*** 依赖注入 start dao/service/===*/@Autowiredprivate CarService carService;// --------------------------------------- 华丽分割线 ------------------------------/*********************************查询列表【不分页】***********************************************//*** 【不分页 => 查询列表 => 无条件】* @Title: listAll * @Description: TODO(这里用一句话描述这个方法的作用) * @param @return 设定文件 * @author* @return String 返回类型 * @throws*/@RequestMapping(value = "/listAll")public String listAll(Car car, Model model, HttpServletRequest request, HttpServletResponse response){List<Car> listAll = carService.listAll();model.addAttribute("list", listAll);return "car/car";}/*** 【不分页=》查询列表=>有条件】* @Title: listByEntity * @Description: TODO(这里用一句话描述这个方法的作用) * @param @return 设定文件 * @author* @return String 返回类型 * @throws*/@RequestMapping(value = "/listByEntity")public String listByEntity(Car car, Model model, HttpServletRequest request, HttpServletResponse response){List<Car> listAll = carService.listAllByEntity(car);model.addAttribute("list", listAll);return "car/car";}/*** 【不分页=》查询列表=>有条件】* @Title: listByMap * @Description: TODO(这里用一句话描述这个方法的作用) * @param @return 设定文件 * @author * @return String 返回类型 * @throws*/@RequestMapping(value = "/listByMap")public String listByMap(Car car, Model model, HttpServletRequest request, HttpServletResponse response){//通过map查询Map<String,Object> params = new HashMap<String,Object>();if(!isEmpty(car.getItemId())){params.put("itemId", car.getItemId());}if(!isEmpty(car.getUserId())){params.put("userId", car.getUserId());}if(!isEmpty(car.getNum())){params.put("num", car.getNum());}if(!isEmpty(car.getTotal())){params.put("total", car.getTotal());}List<Car> listAll = carService.listByMap(params);model.addAttribute("list", listAll);return "car/car";}/*********************************查询列表【分页】***********************************************//*** 分页查询 返回list对象(通过对象)* * @param request* @param response* @return*/@RequestMapping(value = "/findByObj")public String findByObj(Car car, Model model, HttpServletRequest request, HttpServletResponse response) {//分页查询Pager<Car> pagers = carService.findByEntity(car);model.addAttribute("pagers", pagers);//存储查询条件model.addAttribute("obj", car);return "car/car";}/*** 分页查询 返回list对象(通过对By Sql)* * @param request* @param response* @return*/@RequestMapping(value = "/findBySql")public String findBySql(Car car, Model model, HttpServletRequest request, HttpServletResponse response) {Object attribute = request.getSession().getAttribute("userId");if (attribute == null){return "redirect:/login/uLogin";}JSONObject js = new JSONObject();Integer userId = Integer.valueOf(attribute.toString());//分页查询String sql = "SELECT * FROM car WHERE 1=1 and user_id = "+userId;if(!isEmpty(car.getItemId())){sql += " and itemId like '%"+car.getItemId()+"%'";}if(!isEmpty(car.getUserId())){sql += " and userId like '%"+car.getUserId()+"%'";}if(!isEmpty(car.getNum())){sql += " and num like '%"+car.getNum()+"%'";}if(!isEmpty(car.getTotal())){sql += " and total like '%"+car.getTotal()+"%'";}sql += " ORDER BY ID DESC ";List<Car> listBySqlReturnEntity = carService.listBySqlReturnEntity(sql);model.addAttribute("list", listBySqlReturnEntity);//存储查询条件model.addAttribute("obj", car);return "car/car";}/*** 分页查询 返回list对象(通过Map)* * @param request* @param response* @return*/@RequestMapping(value = "/findByMap")public String findByMap(Car car, Model model, HttpServletRequest request, HttpServletResponse response) {//通过map查询Map<String,Object> params = new HashMap<String,Object>();if(!isEmpty(car.getItemId())){params.put("itemId", car.getItemId());}if(!isEmpty(car.getUserId())){params.put("userId", car.getUserId());}if(!isEmpty(car.getNum())){params.put("num", car.getNum());}if(!isEmpty(car.getTotal())){params.put("total", car.getTotal());}//分页查询Pager<Car> pagers = carService.findByMap(params);model.addAttribute("pagers", pagers);//存储查询条件model.addAttribute("obj", car);return "car/car";}/**********************************【增删改】******************************************************//*** 跳至添加页面* @return*/@RequestMapping(value = "/add")public String add() {return "car/add";}/*** 跳至详情页面* @return*/@RequestMapping(value = "/view")public String view(Model model,HttpServletRequest request,String code) {Object attribute = request.getSession().getAttribute("userId");if (attribute == null){return "redirect:/login/uLogin";}Integer userId = Integer.valueOf(attribute.toString());model.addAttribute("code", code);return "car/view";}/*** 添加执行* @return*/@RequestMapping(value = "/exAdd")@ResponseBodypublic String exAdd(Car car, Model model, HttpServletRequest request, HttpServletResponse response) {Object attribute = request.getSession().getAttribute("userId");JSONObject js = new JSONObject();if (attribute == null){js.put("res", 0);return js.toJSONString();}Integer userId = Integer.valueOf(attribute.toString());car.setUserId(userId);Item load = itemService.load(car.getItemId());String price = load.getPrice();Double valueOf = Double.valueOf(price);car.setPrice(valueOf);if (load.getZk() != null){valueOf = (valueOf*load.getZk())/10;BigDecimal bg = new BigDecimal(valueOf).setScale(2, RoundingMode.UP);car.setPrice(bg.doubleValue());valueOf= bg.doubleValue();}Integer num = car.getNum();Double t = valueOf*num;BigDecimal bg = new BigDecimal(t).setScale(2, RoundingMode.UP);double doubleValue = bg.doubleValue();car.setTotal(doubleValue+"");carService.insert(car);js.put("res", 1);return js.toJSONString();}/*** 跳至修改页面* @return*/@RequestMapping(value = "/update")public String update(Integer id,Model model) {Car obj = carService.load(id);model.addAttribute("obj",obj);return "car/update";}@RequestMapping(value = "/js")@ResponseBodypublic String js(@RequestBody List<CarDto> list,Model model,HttpServletRequest request) {Object attribute = request.getSession().getAttribute("userId");JSONObject js = new JSONObject();if (attribute == null){js.put("res", 0);return js.toJSONString();}Integer userId = Integer.valueOf(attribute.toString());String key = "car_"+userId;request.getSession().setAttribute(key, list);js.put("res", 1);return js.toJSONString();}@RequestMapping(value = "/js2")@ResponseBodypublic String js2(Car car, Model model, HttpServletRequest request, HttpServletResponse response) {Object attribute = request.getSession().getAttribute("userId");JSONObject js = new JSONObject();if (attribute == null){js.put("res", 0);return js.toJSONString();}Integer userId = Integer.valueOf(attribute.toString());car.setUserId(userId);Item load = itemService.load(car.getItemId());String price = load.getPrice();Long valueOf = Long.valueOf(price);Integer num = car.getNum();Long t = valueOf*num;car.setTotal(t.toString());carService.insert(car);String key = "car_"+userId;List<CarDto> list = new ArrayList<CarDto>();CarDto d = new CarDto();d.setId(car.getId());d.setNum(car.getNum());list.add(d);request.getSession().setAttribute(key, list);js.put("res", 1);return js.toJSONString();}/*** 添加修改* @return*/@RequestMapping(value = "/exUpdate")public String exUpdate(Car car, Model model, HttpServletRequest request, HttpServletResponse response) {//1.通过实体类修改,可以多传修改条件carService.updateById(car);//2.通过主键id修改//carService.updateById(car);return "redirect:/car/findBySql.action";}/*** 删除通过主键* @return*/@RequestMapping(value = "/delete")@ResponseBodypublic String delete(Integer id, Model model, HttpServletRequest request, HttpServletResponse response) {///1.通过主键删除carService.deleteById(id);/*以下是多种删除方式*/////2.通过实体条件删除//carService.deleteByEntity(car);////3.通过参数删除////通过map查询//Map<String,Object> params = new HashMap<String,Object>();//// if(!isEmpty(car.getItemId())){// params.put("itemId", car.getItemId());//}// // if(!isEmpty(car.getUserId())){// params.put("userId", car.getUserId());//}// // if(!isEmpty(car.getNum())){// params.put("num", car.getNum());//}// // if(!isEmpty(car.getTotal())){// params.put("total", car.getTotal());//}// //carService.deleteByMap(params);////4.状态删除//Car load = carService.getById(car.getId())//load.setIsDelete(1);//carService.update(load);//5.状态删除//Car load = carService.load(id);//load.setIsDelete(1);//carService.update(load);return "redirect:/car/findBySql.action";}// --------------------------------------- 华丽分割线 ------------------------------// --------------------------------------- 【下面是ajax操作的方法。】 ------------------------------/*********************************查询列表【不分页】***********************************************//*** 【不分页 => 查询列表 => 无条件】* @Title: listAll * @Description: TODO(这里用一句话描述这个方法的作用) * @param @return 设定文件 * @author* @return String 返回类型 * @throws*/@RequestMapping(value = "/listAllJson", method = RequestMethod.POST)@ResponseBodypublic String listAllJson(Car car, HttpServletRequest request, HttpServletResponse response){List<Car> listAll = carService.listAll();JSONObject jsonObject = new JSONObject();jsonObject.put("list", listAll);jsonObject.put("obj", car);return jsonObject.toString();}/*** 【不分页=》查询列表=>有条件】* @Title: listByEntity * @Description: TODO(这里用一句话描述这个方法的作用) * @param @return 设定文件 * @author* @return String 返回类型 * @throws*/@RequestMapping(value = "/listByEntityJson", method = RequestMethod.POST)@ResponseBodypublic String listByEntityJson(Car car, HttpServletRequest request, HttpServletResponse response){List<Car> listAll = carService.listAllByEntity(car);JSONObject jsonObject = new JSONObject();jsonObject.put("list", listAll);jsonObject.put("obj", car);return jsonObject.toString();}/*** 【不分页=》查询列表=>有条件】* @Title: listByMap * @Description: TODO(这里用一句话描述这个方法的作用) * @param @return 设定文件 * @author * @return String 返回类型 * @throws*/@RequestMapping(value = "/listByMapJson", method = RequestMethod.POST)@ResponseBodypublic String listByMapJson(Car car,HttpServletRequest request, HttpServletResponse response){//通过map查询Map<String,Object> params = new HashMap<String,Object>();if(!isEmpty(car.getItemId())){params.put("itemId", car.getItemId());}if(!isEmpty(car.getUserId())){params.put("userId", car.getUserId());}if(!isEmpty(car.getNum())){params.put("num", car.getNum());}if(!isEmpty(car.getTotal())){params.put("total", car.getTotal());}List<Car> listAll = carService.listByMap(params);JSONObject jsonObject = new JSONObject();jsonObject.put("list", listAll);jsonObject.put("obj", car);return jsonObject.toString();}/*** 分页查询 返回list json(通过对象)* * @param request* @param response* @return*/@RequestMapping(value = "/findByObjJson", method = RequestMethod.POST)@ResponseBodypublic String findByObjByEntityJson(Car car, HttpServletRequest request, HttpServletResponse response) {//分页查询Pager<Car> pagers = carService.findByEntity(car);JSONObject jsonObject = new JSONObject();jsonObject.put("pagers", pagers);jsonObject.put("obj", car);return jsonObject.toString();}/*** 分页查询 返回list json(通过Map)* * @param request* @param response* @return*/@RequestMapping(value = "/findByMapJson", method = RequestMethod.POST)@ResponseBodypublic String findByMapJson(Car car,HttpServletRequest request, HttpServletResponse response) {//通过map查询Map<String,Object> params = new HashMap<String,Object>();if(!isEmpty(car.getItemId())){params.put("itemId", car.getItemId());}if(!isEmpty(car.getUserId())){params.put("userId", car.getUserId());}if(!isEmpty(car.getNum())){params.put("num", car.getNum());}if(!isEmpty(car.getTotal())){params.put("total", car.getTotal());}//分页查询Pager<Car> pagers = carService.findByMap(params);JSONObject jsonObject = new JSONObject();jsonObject.put("pagers", pagers);jsonObject.put("obj", car);return jsonObject.toString();}/*** ajax 添加* @param * @return*/@RequestMapping(value = "/exAddJson", method = RequestMethod.POST)@ResponseBodypublic String exAddJson(Car car, Model model, HttpServletRequest request, HttpServletResponse response) {carService.insert(car);JSONObject jsonObject = new JSONObject();jsonObject.put("message", "添加成功");return jsonObject.toString();}/*** ajax 修改* @param * @return*/@RequestMapping(value = "/exUpdate.json", method = RequestMethod.POST)@ResponseBodypublic String exUpdateJson(Car car, Model model, HttpServletRequest request, HttpServletResponse response) {//1.通过实体类修改,可以多传修改条件carService.updateById(car);//2.通过主键id修改//carService.updateById(car);JSONObject jsonObject = new JSONObject();jsonObject.put("message", "修改成功");return jsonObject.toString();}/*** ajax 删除* @return*/@RequestMapping(value = "/delete.json", method = RequestMethod.POST)@ResponseBodypublic String exDeleteJson(Integer id, Model model, HttpServletRequest request, HttpServletResponse response) {///1.通过主键删除carService.deleteById(id);/*以下是多种删除方式*/////2.通过实体条件删除//carService.deleteByEntity(car);////3.通过参数删除// //通过map查询//Map<String,Object> params = new HashMap<String,Object>();//// if(!isEmpty(car.getItemId())){// params.put("itemId", car.getItemId());//}// // if(!isEmpty(car.getUserId())){// params.put("userId", car.getUserId());//}// // if(!isEmpty(car.getNum())){// params.put("num", car.getNum());//}// // if(!isEmpty(car.getTotal())){// params.put("total", car.getTotal());//}// //carService.deleteByMap(params);////4.状态删除//Car load = carService.getById(car.getId())//load.setIsDelete(1);//carService.updateById(load);//5.状态删除//Car load = carService.load(id);//load.setIsDelete(1);//carService.updateById(load);JSONObject jsonObject = new JSONObject();jsonObject.put("message", "删除成功");return jsonObject.toString();}/*** 单文件上传* @param file* @param request* @param model* @return*/@RequestMapping(value = "/saveFile") public String saveFile(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, Model model) { System.out.println("开始"); String path = request.getSession().getServletContext().getRealPath("/upload"); String fileName = file.getOriginalFilename(); System.out.println(path); File targetFile = new File(path, fileName); if(!targetFile.exists()){ targetFile.mkdirs(); } //保存 try { file.transferTo(targetFile); } catch (Exception e) { e.printStackTrace(); } return ""; } /*** springMvc多文件上传* @param files* @param id* @return*/@RequestMapping(value = "/saveFiles")public String saveFiles(@RequestParam("file") CommonsMultipartFile[] files,Integer id,HttpServletRequest request){for(int i = 0;i<files.length;i++){System.out.println("fileName---------->" + files[i].getOriginalFilename());if(!files[i].isEmpty()){int pre = (int) System.currentTimeMillis();try {//拿到输出流,同时重命名上传的文件String filePath = request.getRealPath("/upload");File f=new File(filePath);if(!f.exists()){f.mkdirs();}String fileNmae=new Date().getTime() + files[i].getOriginalFilename();File file=new File(filePath+"/"+pre + files[i].getOriginalFilename());if(!file.exists()){file.createNewFile();}files[i].transferTo(file);} catch (Exception e) {e.printStackTrace();System.out.println("上传出错");}}}return "";}// --------------------------------------- 华丽分割线 ------------------------------}
登录管理控制层:
@Controller@RequestMapping("/login")public class LoginController extends BaseController{@Autowiredprivate ManageService manageService;@Autowiredprivate UserService userService;@Autowiredprivate ItemOrderService itemOrderService;@Autowiredprivate ItemService itemService;@Autowiredprivate CarService carService;@Autowiredprivate ItemCategoryService itemCategoryService;@Autowiredprivate OrderDetailService orderDetailService;/*** 跳转登陆* @return*/@RequestMapping("/login")public String login(){return "login/mLogin";}@RequestMapping("/uLogin")public String uLogin(){return "login/uLogin";}@RequestMapping("/res")public String res(){return "login/res";}@RequestMapping("/toRes")public String toRes(User u){userService.insert(u);return "login/uLogin";}@RequestMapping("/uIndex")public String uIndex(Model model,Item item,String prices,Integer xl, HttpServletRequest request){String sql2 = "SELECT * FROM item_category WHERE isDelete = 0 and pid is null";sql2 += " ORDER BY ID DESC ";List<ItemCategory> fatherList = itemCategoryService.listBySqlReturnEntity(sql2);List<CategoryDto> list = new ArrayList<CategoryDto>();if (!CollectionUtils.isEmpty(fatherList)){for (ItemCategory ic : fatherList){CategoryDto dto = new CategoryDto();dto.setFather(ic);//查询儿子String sql3 = "SELECT * FROM item_category WHERE isDelete = 0 and pid = "+ic.getId();List<ItemCategory> childrens = itemCategoryService.listBySqlReturnEntity(sql3);dto.setChildrens(childrens);list.add(dto);}System.out.println("====================================================");model.addAttribute("lbs",list);}//在redis中查询所有分类/*String string = RedisUtil.getJedis().get("lbs");List<CategoryDto> parseArray = JSONArray.parseArray(string, CategoryDto.class);System.out.println(JSONObject.toJSONString(parseArray));model.addAttribute("lbs",parseArray);*/// 1-500//热销List<Item> listBySqlReturnEntity = itemService.listBySqlReturnEntity("SELECT * FROM item WHERE 1=1 and isDelete =0 order by gmNum desc limit 0,10");model.addAttribute("rxs",listBySqlReturnEntity);//折扣List<Item> zks = itemService.listBySqlReturnEntity("SELECT * FROM item WHERE 1=1 and isDelete =0 and zk is not null order by zk desc limit 0,10");model.addAttribute("zks",zks);//做推荐Object attribute = request.getSession().getAttribute("userId");if (attribute != null){Integer userId = Integer.valueOf(attribute.toString());//协同过滤List<Item> tjs = getListByUCF(userId);model.addAttribute("tjs",tjs);}model.addAttribute("obj",item);model.addAttribute("prices",prices);model.addAttribute("xl",xl);return "login/uIndex";}private List<Item> getListByUCF(Integer userId) {List<Item> returnList = new ArrayList<Item> ();List<User> listAll = userService.listAll();List<Integer> userIds = new ArrayList<Integer>();List<ItemDto> res = new ArrayList<ItemDto>();//判断这些人,有咩有买过东西for (User u : listAll){userIds.add(u.getId());}//输入用户总量int N = userIds.size();int[][] sparseMatrix = new int[N][N];//建立用户稀疏矩阵,用于用户相似度计算【相似度矩阵】Map<String, Integer> userItemLength = new HashMap<String, Integer>();//存储每一个用户对应的不同物品总数 eg: A 3Map<String, Set<String>> itemUserCollection = new HashMap<String, Set<String>>();//建立物品到用户的倒排表 eg: a A BSet<String> items = new HashSet<String>();//辅助存储物品集合Map<String, Integer> userID = new HashMap<String, Integer>();//辅助存储每一个用户的用户ID映射Map<Integer, String> idUser = new HashMap<Integer, String>();//辅助存储每一个ID对应的用户映射Integer a = 0;for (User u : listAll){ItemOrder or = new ItemOrder();or.setUserId(u.getId());List<ItemOrder> listAllByEntity = itemOrderService.listAllByEntity(or);if (!CollectionUtils.isEmpty(listAllByEntity)){for (ItemOrder ors : listAllByEntity){OrderDetail de = new OrderDetail();de.setOrderId(ors.getId());List<OrderDetail> listAllByEntity2 = orderDetailService.listAllByEntity(de);if (!CollectionUtils.isEmpty(listAllByEntity2)){for (OrderDetail dd : listAllByEntity2){items.add(String.valueOf(dd.getItemId()));}}}}String[] user_item = new String[items.size()+1];List<String> isitems = new ArrayList<String>(items);user_item[0] = String.valueOf(u.getId());for(int k = 1; k < items.size()+1 ; k++){user_item[k] = String.valueOf(isitems.get(k-1));}int length = user_item.length;userItemLength.put(user_item[0], length);//eg: A 3userID.put(user_item[0], a);//用户ID与稀疏矩阵建立对应关系idUser.put(a, user_item[0]);//建立物品--用户倒排表for(int j = 1; j < length; j ++){if(items.contains(user_item[j])){//如果已经包含对应的物品--用户映射,直接添加对应的用户Set<String> set2 = itemUserCollection.get(user_item[j]);if (!CollectionUtils.isEmpty(set2)){set2.add(user_item[0]);}else{itemUserCollection.put(user_item[j], new HashSet<String>());//创建物品--用户倒排关系itemUserCollection.get(user_item[j]).add(user_item[0]);}//itemUserCollection.get(user_item[j]).add(user_item[0]);}else{//否则创建对应物品--用户集合映射items.add(user_item[j]);itemUserCollection.put(user_item[j], new HashSet<String>());//创建物品--用户倒排关系itemUserCollection.get(user_item[j]).add(user_item[0]);}}a++;}System.out.println(itemUserCollection.toString());//计算相似度矩阵【稀疏】Set<Entry<String, Set<String>>> entrySet = itemUserCollection.entrySet();Iterator<Entry<String, Set<String>>> iterator = entrySet.iterator();while(iterator.hasNext()){Set<String> commonUsers = iterator.next().getValue();for (String user_u : commonUsers) {for (String user_v : commonUsers) {if(user_u.equals(user_v)){continue;}sparseMatrix[userID.get(user_u)][userID.get(user_v)] += 1;//计算用户u与用户v都有正反馈的物品总数}}}System.out.println(userItemLength.toString());String recommendUser = String.valueOf(userId);System.out.println(userID.get(recommendUser));//计算用户之间的相似度【余弦相似性】Integer s = userID.get(recommendUser);int recommendUserId = 0;if (s != null){recommendUserId = s;}else{}//判断当前用户的indexInteger index = 0;for(int j = 0; j < userIds.size(); j ++){if (userIds.get(j).equals(recommendUserId)){index = j;}}recommendUserId = index;for (int j = 0;j < sparseMatrix.length; j++) {if(j != recommendUserId){//System.out.println(idUser.get(recommendUserId)+"--"+idUser.get(j)+"相似度:"+sparseMatrix[recommendUserId][j]/Math.sqrt(userItemLength.get(idUser.get(recommendUserId))*userItemLength.get(idUser.get(j))));}}//计算指定用户recommendUser的物品推荐度for(String item: items){//遍历每一件物品Set<String> users = itemUserCollection.get(item);//得到购买当前物品的所有用户集合if (users == null){continue;}//double itemRecommendDegree = 0.0;for(String user: users){itemRecommendDegree += sparseMatrix[userID.get(user)][userID.get(user)]/Math.sqrt(userItemLength.get(recommendUser)*userItemLength.get(recommendUser));//推荐度计算}System.out.println("The item "+item+" for "+recommendUser +"'s recommended degree:"+itemRecommendDegree);ItemDto itd = new ItemDto();itd.setItemId(Integer.valueOf(item));itd.setItemRecommendDegree(itemRecommendDegree);res.add(itd);}if (!CollectionUtils.isEmpty(res)){Collections.sort(res, new Comparator<ItemDto>() {public int compare(ItemDto o1, ItemDto o2) {return pare(o1.getItemRecommendDegree(),o2.getItemRecommendDegree());}});Integer b = 1;for (ItemDto i :res){if(b<=10){Item byId = itemService.getById(i.getItemId());returnList.add(byId);}b++;}}return returnList;}@RequestMapping("/mtuichu")public String mtuichu(HttpServletRequest request){//request.getSession().invalidate();return "login/mLogin";}@RequestMapping("/welcome")private String welcome(){return "login/welcome";}@RequestMapping("/toLogin")public String toLogin(Manage manage, HttpServletRequest request, HttpServletResponse response){Manage byEntity = manageService.getByEntity(manage);if(byEntity == null){return "redirect:/login/mtuichu";}else{/*request.getSession().setAttribute("role", 1);request.getSession().setAttribute("username", byEntity.getUserName());request.getSession().setAttribute("userId", byEntity.getId());*/}return "login/mIndex";}@RequestMapping("/utoLogin")public String utoLogin(User manage, HttpServletRequest request, HttpServletResponse response){User byEntity = userService.getByEntity(manage);if(byEntity == null){return "redirect:/login/res.action";}else{request.getSession().setAttribute("role", 2);request.getSession().setAttribute("username", byEntity.getUserName());request.getSession().setAttribute("userId", byEntity.getId());}return "redirect:/login/uIndex.action";}@RequestMapping("/pass")public String pass(HttpServletRequest request){Object attribute = request.getSession().getAttribute("userId");if (attribute == null){return "redirect:/login/uLogin.action";}Integer userId = Integer.valueOf(attribute.toString());User load = userService.load(userId);request.setAttribute("obj", load);return "login/pass";}@RequestMapping("/upass")@ResponseBodypublic String upass(HttpServletRequest request,String password){Object attribute = request.getSession().getAttribute("userId");JSONObject j = new JSONObject();if (attribute == null){j.put("res", 0);return j.toString();}Integer userId = Integer.valueOf(attribute.toString());User load = userService.load(userId);load.setPassWord(password);userService.updateById(load);j.put("res", 1);return j.toString();}//@RequestMapping("/toLogin2")//public String toLogin(Student student, HttpServletRequest request, HttpServletResponse response){//student.setIsdel(0);//Student byEntity = studentService.getByEntity(student);//if(byEntity == null){//return "redirect:/login/login.action";//}else{//request.getSession().setAttribute("role",2);//request.getSession().setAttribute("type",3);//request.getSession().setAttribute("username", byEntity.getXh());//request.getSession().setAttribute("userId", byEntity.getId());//}//return "login/index";//}/*** 退出* @param request* @param response* @return*/@RequestMapping("/tuichu")public String tuichu( HttpServletRequest request, HttpServletResponse response){HttpSession session = request.getSession();session.invalidate();return "login/login";}@RequestMapping("/uTui")public String uTui( HttpServletRequest request, HttpServletResponse response){HttpSession session = request.getSession();session.invalidate();return "redirect:/login/uLogin.action";}@RequestMapping("/head")private String head(){return "inc/head";}@RequestMapping("/left")private String left(){return "inc/left";}@RequestMapping("/main")private String main(HttpServletRequest request){Object attribute = request.getSession().getAttribute("userId");if (attribute == null){return "redirect:/login/uLogin.action";}Integer userId = Integer.valueOf(attribute.toString());User load = userService.load(userId);request.setAttribute("user", load);return "login/main";}@RequestMapping("/info")private String info(HttpServletRequest request){Object attribute = request.getSession().getAttribute("userId");Integer userId = Integer.valueOf(attribute.toString());User load = userService.load(userId);request.setAttribute("user", load);return "login/info";}}
源码获取:俺的博客首页 "资源" 里下载!