我的编程空间,编程开发者的网络收藏夹
学习永远不晚

Java实战网上电子书城的实现流程

短信预约 -IT技能 免费直播动态提醒
省份

北京

  • 北京
  • 上海
  • 天津
  • 重庆
  • 河北
  • 山东
  • 辽宁
  • 黑龙江
  • 吉林
  • 甘肃
  • 青海
  • 河南
  • 江苏
  • 湖北
  • 湖南
  • 江西
  • 浙江
  • 广东
  • 云南
  • 福建
  • 海南
  • 山西
  • 四川
  • 陕西
  • 贵州
  • 安徽
  • 广西
  • 内蒙
  • 西藏
  • 新疆
  • 宁夏
  • 兵团
手机号立即预约

请填写图片验证码后获取短信验证码

看不清楚,换张图片

免费获取短信验证码

Java实战网上电子书城的实现流程

项目描述: spring mvc +jsp实现的简单书城项目,可以在支付宝沙箱内实现支付

运行环境: jdk8+tomcat9+mysql+IntelliJ IDEA

项目技术: spring+spring mvc+mybatis+jsp+maven

 后台管理员图书管理代码:

@Controller
@RequestMapping("/admin/book")
@RequiresPermissions("book-manage")
public class AdminBookController {
 
    @Autowired
    private IBookInfoService bookInfoService;
 
    @Autowired
    private BookDescMapper bookDescMapper;
 
    @Autowired
    private IStoreService storeService;
 
    @Value("${image.url.prefix}")
    private String urlPrefix;
 
    @RequestMapping("toAddition")
    @RequiresPermissions("book-add")
    public String toAddition() {
        return "admin/book/add";
    }
 
    
    @RequestMapping("/addition")
    @RequiresPermissions("book-add")
    public String addBook(BookInfo bookInfo, String bookDesc, MultipartFile pictureFile, HttpServletRequest request) throws Exception {
 
        uploadPicture(bookInfo, pictureFile, request);
        bookInfoService.saveBook(bookInfo, bookDesc);
 
        return "redirect:/admin/book/list";
    }
 
    
    @RequestMapping(value = "/list")
    @RequiresPermissions("book-query")
    public String bookList(@RequestParam(defaultValue = "", required = false) String keywords,
                           @RequestParam(value = "page", defaultValue = "1", required = false) int page,
                           HttpSession session,
                           Model model) {
        keywords = keywords.trim();
        Store store = (Store) session.getAttribute("loginStore");
 
        if (store != null) {
            PageInfo<BookInfo> books = bookInfoService.findBookListByCondition(keywords, 0, page, 10, store.getStoreId());
            model.addAttribute("bookPageInfo", books);
            model.addAttribute("keywords", keywords);
        } else {
            model.addAttribute("exception", "您请求的资源不存在");
            return "exception";
        }
 
        return "admin/book/list";
    }
 
    
    @RequestMapping("/echo")
    @RequiresPermissions("book-edit")
    public String echo(int bookId, Model model) throws BSException {
 
        BookInfo bookInfo = bookInfoService.adminFindById(bookId);
 
        BookDesc bookDesc = bookDescMapper.selectByPrimaryKey(bookInfo.getBookId());
 
        model.addAttribute("bookInfo", bookInfo);
 
        model.addAttribute("bookDesc", bookDesc);
 
        return "admin/book/edit";
    }
 
    @RequestMapping("/update")
    @RequiresPermissions("book-edit")
    public String updateBook(BookInfo bookInfo, String bookDesc, String keywords, MultipartFile pictureFile, HttpServletRequest request, RedirectAttributes ra) throws Exception {
        uploadPicture(bookInfo, pictureFile, request);
        BookInfo originBook = bookInfoService.findById(bookInfo.getBookId());
        bookInfoService.updateBook(bookInfo, bookDesc);
 
        //更新图片后,删除原来的图片
        String realPath = request.getServletContext().getRealPath("/");
        File uploadPic = new File(realPath + originBook.getImageUrl());
        uploadPic.delete();
        //重定向到书籍列表
        ra.addAttribute("keywords", keywords);
        return "redirect:/admin/book/list";
    }
 
    @RequestMapping("/deletion/{bookId}")
    @RequiresPermissions("book-delete")
    public String deletion(@PathVariable("bookId") int bookId, String keywords, RedirectAttributes ra, HttpServletRequest request) throws BSException {
        BookInfo bookInfo = bookInfoService.findById(bookId);
        String realPath = request.getServletContext().getRealPath("/");
        File uploadPic = new File(realPath + bookInfo.getImageUrl());
        uploadPic.delete();
        bookInfoService.deleteBook(bookId);
        ra.addAttribute("keywords", keywords);
        return "redirect:/admin/book/list";
    }
 
    @RequestMapping("/shelf")
    @RequiresPermissions("book-shelf")
    public String bookOffShelf(int bookId, int isShelf, String keywords, RedirectAttributes ra) {
 
        bookInfoService.changeShelfStatus(bookId, isShelf);
        ra.addAttribute("keywords", keywords);
        return "redirect:/admin/book/list";
    }
 
    private void uploadPicture(BookInfo bookInfo, MultipartFile pictureFile, HttpServletRequest request) throws IOException {
        if (pictureFile != null) {
            if (!StringUtils.isEmpty(pictureFile.getOriginalFilename())) {
                String realPath = request.getServletContext().getRealPath("/" + urlPrefix);
                //原始文件名称
                String pictureFileName = pictureFile.getOriginalFilename();
                //新文件名称
                String newFileName = IDUtils.genShortUUID() + pictureFileName.substring(pictureFileName.lastIndexOf("."));
 
                //上传图片
                File uploadPic = new File(realPath + File.separator + newFileName);
 
                //向磁盘写文件
                pictureFile.transferTo(uploadPic);
                bookInfo.setImageUrl(urlPrefix + File.separator + newFileName);
            }
        }
    }
 
}

书信息控制层:


@Controller
@RequestMapping("/book")
public class BookInfoController {
 
 
 
    @Autowired
    private IBookInfoService bookInfoService;
 
    @Autowired
    private BookDescMapper bookDescMapper;
 
    
    @RequestMapping("/info/{bookId}")
    public String bookInfo(@PathVariable("bookId") Integer bookId, Model model) throws BSException {
        //查询书籍
        BookInfo bookInfo = bookInfoService.findById(bookId);
        //查询书籍推荐列表
        List<BookInfo> recommendBookList = bookInfoService.findBookListByCateId(bookInfo.getBookCategoryId(), 1, 5);
        //查询书籍详情
        BookDesc bookDesc = bookDescMapper.selectByPrimaryKey(bookId);
        //增加访问量
        bookInfoService.addLookMount(bookInfo);
        Collections.shuffle(recommendBookList);
        model.addAttribute("bookInfo", bookInfo);
        model.addAttribute("bookDesc", bookDesc);
        model.addAttribute("recommendBookList", recommendBookList);
        return "book_info";
    }
 
 
    
    @RequestMapping("/list")
    public String bookSearchList(@RequestParam(defaultValue = "", required = false) String keywords,
                                 @RequestParam(defaultValue = "0", required = false) int cateId,//分类Id,默认为0,即不按照分类Id查
                                 @RequestParam(defaultValue = "1", required = false) int page,
                                 @RequestParam(defaultValue = "6", required = false) int pageSize,
                                 Model model) {
        keywords = keywords.trim();
        PageInfo<BookInfo> bookPageInfo = bookInfoService.findBookListByCondition(keywords, cateId, page, pageSize,0);//storeId为0,不按照商店Id查询
 
        model.addAttribute("bookPageInfo", bookPageInfo);
 
        model.addAttribute("keywords", keywords);
 
        model.addAttribute("cateId", cateId);
 
        return "book_list";
    }
 
}

用户管理控制层:

@Controller
@RequestMapping("/user")
public class UserController {
 
 
    @Autowired
    private IUserService userService;
 
    @Autowired
    private IMailService mailService;
 
    @Autowired
    private IStoreService storeService;
 
    @Value("${mail.fromMail.addr}")
    private String from;
 
    @Value("${my.ip}")
    private String ip;
 
    private final String USERNAME_PASSWORD_NOT_MATCH = "用户名或密码错误";
 
    private final String USERNAME_CANNOT_NULL = "用户名不能为空";
 
    @RequestMapping("/login")
    public String login(@RequestParam(value = "username", required = false) String username,
                        @RequestParam(value = "password", required = false) String password,
                        HttpServletRequest request, Model model) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return "login";
        }
        //未认证的用户
        Subject userSubject = SecurityUtils.getSubject();
        if (!userSubject.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
 
            token.setRememberMe(false);//禁止记住我功能
            try {
 
                //登录成功
                userSubject.login(token);
                User loginUser = (User) userSubject.getPrincipal();
                request.getSession().setAttribute("loginUser", loginUser);
                Store store = storeService.findStoreByUserId(loginUser.getUserId());
                request.getSession().setAttribute("loginStore", store);
 
 
                SavedRequest savedRequest = WebUtils.getSavedRequest(request);
                String url = "/";
                if (savedRequest != null) {
                    url = savedRequest.getRequestUrl();
                    if(url.contains(request.getContextPath())){
                        url = url.replace(request.getContextPath(),"");
                    }
                }
                if(StringUtils.isEmpty(url) || url.equals("/favicon.ico")){
                    url = "/";
                }
 
                return "redirect:" + url;
 
            } catch (UnknownAccountException | IncorrectCredentialsException uae) {
                model.addAttribute("loginMsg", USERNAME_PASSWORD_NOT_MATCH);
                return "login";
            } catch (LockedAccountException lae) {
                model.addAttribute("loginMsg", "账户已被冻结!");
                return "login";
            } catch (AuthenticationException ae) {
                model.addAttribute("loginMsg", "登录失败!");
                return "login";
            }
 
        } else {
            //用户已经登录
            return "redirect:/index";
        }
 
    }
 
    @RequestMapping("/info")
    public String personInfo(){
        return "user_info";
    }
 
    
    //shiro框架帮我们注销
    @RequestMapping("/logout")
    @CacheEvict(cacheNames="authorizationCache",allEntries = true)
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "redirect:/page/login";
    }
 
    
    @RequestMapping("/checkUserExist")
    @ResponseBody
    public BSResult checkUserExist(String username) {
        if (StringUtils.isEmpty(username)) {
            return BSResultUtil.build(200, USERNAME_CANNOT_NULL, false);
        }
 
        return userService.checkUserExistByUsername(username);
    }
 
    
    @RequestMapping("/register")
    public String register(User user, Model model) {
 
        BSResult isExist = checkUserExist(user.getUsername());
 
        //尽管前台页面已经用ajax判断用户名是否存在,
        // 为了防止用户不是点击前台按钮提交表单造成的错误,后台也需要判断
        if ((Boolean) isExist.getData()) {
        	user.setActive("1");
            BSResult bsResult = userService.saveUser(user);
            //获得未激活的用户
            User userNotActive = (User) bsResult.getData();
          
            model.addAttribute("username", user.getUsername());
            return "register_success";
        } else {
 
            //用户名已经存在,不能注册
            model.addAttribute("registerError", isExist.getMessage());
            return "register";
        }
 
    }
 
    @RequestMapping("/active")
    public String activeUser(String activeCode, Model model) {
        BSResult bsResult = userService.activeUser(activeCode);
        if (!StringUtils.isEmpty(bsResult.getData())) {
            model.addAttribute("username", bsResult.getData());
            return "active_success";
        } else {
            model.addAttribute("failMessage", bsResult.getMessage());
            return "fail";
        }
    }
 
    @RequestMapping("/update")
    @ResponseBody
    public BSResult updateUser(User user, HttpSession session){
        User loginUser = (User) session.getAttribute("loginUser");
        loginUser.setNickname(user.getNickname());
        loginUser.setLocation(user.getLocation());
        loginUser.setDetailAddress(user.getDetailAddress());
        loginUser.setGender(user.getGender());
        loginUser.setUpdated(new Date());
        loginUser.setPhone(user.getPhone());
        loginUser.setIdentity(user.getIdentity());
        loginUser.setPhone(user.getPhone());
        BSResult bsResult = userService.updateUser(loginUser);
        session.setAttribute("loginUser", loginUser);
        return bsResult;
    }
 
    @RequestMapping("/password/{userId}")
    @ResponseBody
    public BSResult changePassword(@PathVariable("userId") int userId,String oldPassword,String newPassword){
        if(StringUtils.isEmpty(oldPassword) || StringUtils.isEmpty(newPassword)){
            return BSResultUtil.build(400, "密码不能为空");
        }
        return userService.compareAndChange(userId,oldPassword,newPassword);
    }
 
}

到此这篇关于Java实战网上电子书城的实现流程的文章就介绍到这了,更多相关Java 网上电子书城内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

Java实战网上电子书城的实现流程

下载Word文档到电脑,方便收藏和打印~

下载Word文档

猜你喜欢

Java中如何实现网上电子书城

这篇文章将为大家详细讲解有关Java中如何实现网上电子书城,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。项目描述: spring mvc +jsp实现的简单书城项目,可以在支付宝沙箱内实现支付运行环境:
2023-06-22

编程热搜

  • Python 学习之路 - Python
    一、安装Python34Windows在Python官网(https://www.python.org/downloads/)下载安装包并安装。Python的默认安装路径是:C:\Python34配置环境变量:【右键计算机】--》【属性】-
    Python 学习之路 - Python
  • chatgpt的中文全称是什么
    chatgpt的中文全称是生成型预训练变换模型。ChatGPT是什么ChatGPT是美国人工智能研究实验室OpenAI开发的一种全新聊天机器人模型,它能够通过学习和理解人类的语言来进行对话,还能根据聊天的上下文进行互动,并协助人类完成一系列
    chatgpt的中文全称是什么
  • C/C++中extern函数使用详解
  • C/C++可变参数的使用
    可变参数的使用方法远远不止以下几种,不过在C,C++中使用可变参数时要小心,在使用printf()等函数时传入的参数个数一定不能比前面的格式化字符串中的’%’符号个数少,否则会产生访问越界,运气不好的话还会导致程序崩溃
    C/C++可变参数的使用
  • css样式文件该放在哪里
  • php中数组下标必须是连续的吗
  • Python 3 教程
    Python 3 教程 Python 的 3.0 版本,常被称为 Python 3000,或简称 Py3k。相对于 Python 的早期版本,这是一个较大的升级。为了不带入过多的累赘,Python 3.0 在设计的时候没有考虑向下兼容。 Python
    Python 3 教程
  • Python pip包管理
    一、前言    在Python中, 安装第三方模块是通过 setuptools 这个工具完成的。 Python有两个封装了 setuptools的包管理工具: easy_install  和  pip , 目前官方推荐使用 pip。    
    Python pip包管理
  • ubuntu如何重新编译内核
  • 改善Java代码之慎用java动态编译

目录