基于javaweb+mysql的ssm+maven图书租赁管理系统(java+ssm+jsp+bootstrap+echarts+mysql)

基于javaweb+mysql的ssm+maven图书租赁管理系统(java+ssm+jsp+bootstrap+echarts+mysql)

运行环境

Java≥8、MySQL≥5.7、Tomcat≥8

开发工具

eclipse/idea/myeclipse/sts等均可配置运行

适用

课程设计,大作业,毕业设计,项目练习,学习演示等

功能说明

基于javaweb+mysql的SSM+Maven图书租赁管理系统(java+ssm+jsp+bootstrap+echarts+mysql)

图书租赁管理系统

项目介绍

图书租赁管理系统,该系统分为管理员与普通读者两种角色; 管理员主要功能包括: 图书管理:添加、修改、删除; 图书分类管理:添加、修改、删除; 借阅信息:还书; 预定信息:确认借书; 归还信息; 统计管理:借书/归还、营业额、销量; 普通读者主要功能包括:预定图书、待拿图书、借阅中、归还信息等;

客户端的充值,使用的支付宝沙箱测试化境

环境需要

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.是否Maven项目: 是;查看源码目录中是否包含pom.xml;若包含,则为maven项目,否则为非maven项目 6.数据库:MySql 8.0版本; 7.lombok插件安装:本项目需要安装lombok插件,否则运行会有异常;

技术栈

  1. 后端:Spring SpringMVC MyBatis 2. 前端:JSP+bootstrap+jQuery+echarts

使用说明

  1. 使用Navicat或者其它工具,在mysql中创建对应名称的数据库,并导入项目的sql文件; 2. 使用IDEA/Eclipse/MyEclipse导入项目,Eclipse/MyEclipse导入时,若为maven项目请选择maven;若为maven项目,导入成功后请执行maven clean;maven install命令,配置tomcat,然后运行; 3. 将项目中db.properties配置文件中的数据库配置改为自己的配置;

  2. 运行项目,输入localhost:8080/bm/

					break;
				}
			}
		} catch (UnsupportedEncodingException e) {
			logger.error("Cookie Decode Error.", e);
		}
		return retValue;
	}

	/**
	 * 得到Cookie的值,
	 * 
	 * @param request
	 * @param cookieName
	 * @return
	 */
	public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) {
		Cookie[] cookieList = request.getCookies();
		if (cookieList == null || cookieName == null){
			return null;			
		}
		String retValue = null;
		try {
			for (int i = 0; i < cookieList.length; i++) {
				if (cookieList[i].getName().equals(cookieName)) {
					retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString);
					break;
				}
			}
		} catch (UnsupportedEncodingException e) {
			logger.error("Cookie Decode Error.", e);
		}
		return retValue;
	}

	/**
	 * 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码
	 */
	public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue) {
		setCookie(request, response, cookieName, cookieValue, -1,"/");
	}

	/**
	 * 设置Cookie的值 在指定时间内生效,但不编码
	 */
	public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage) {
		setCookie(request, response, cookieName, cookieValue, cookieMaxage, false);
@Controller
public class ReaderController {

    @Autowired
    private ReaderService readerService;

    //发送支付请求
    @PostMapping("/balance")
    public void addBalance(Double money,HttpServletRequest request, HttpServletResponse response){
        readerService.addBalance(money,request,response);
    }

    //支付同步通知
    @RequestMapping("/returnUrl")
    public String returnUrl(HttpServletRequest request,HttpServletResponse response){
        readerService.returnUrl(request);
        return "redirect:/pages/reader/bookDatalist.jsp";
    }

    //支付异步通知
    @PostMapping("/notify")
    public void notify(HttpServletRequest request,HttpServletResponse response){
        readerService.notify(request,response);
    }

    @GetMapping("/refreshMoney")
    public ResponseEntity<Double> refreshMoney(HttpServletRequest request){
        return ResponseEntity.ok(readerService.refreshMoney(request));
    }

}

    public void modifyMailDefaultTemplate(Integer id, String defaultTemplate) {
        templateMapper.updateByPrimaryKeySelective(new MailTemplate().setMtId(id).setDefaultTemplate(defaultTemplate));
    }

    //提醒还书
    public void remind(Integer bbId) {
        //查询借阅记录是否还存在
        BorrowBooks borrowBook = borrowBookMapper.queryBorrowBookByBbId(bbId);
        if(borrowBook == null){ //该图书已被归还
            throw new LyException(ExceptionEnum.BORROW_BOOKS_IS_RETURN);
        }
        //获取用户的id查询用户的邮箱
        Integer rId = borrowBook.getRId();
        Reader reader = readerMapper.selectByPrimaryKey(rId);
        if(reader == null){ //用户不存在
            throw new LyException(ExceptionEnum.SERVICE_BUSY);
        }
        MailTemplate mailTemplate = null;
        //实际借书天数(现在的时间-租借的时间)
        int readyDay =  DateUtils.differenceDay(new Date(),borrowBook.getBbTime());
        //最大借书天数 = 应该还书的时间-租借的时间
        int maxDay = DateUtils.differenceDay(borrowBook.getDueTime(),borrowBook.getBbTime());
        //逾期天数 = 实际借书天数 - 最大借书天数
        int overDay = readyDay - maxDay;
        //用户是否逾期
        if(overDay <=0 ){ //还未逾期
            //查询未逾期模板
            mailTemplate = templateMapper.selectByPrimaryKey(1);
            borrowBook.setRemainingDays(maxDay-readyDay);
        }else{
            mailTemplate = templateMapper.selectByPrimaryKey(2);
            borrowBook.setRemainingDays(overDay);
        }

        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
        String url = basePath;

        String aDocument = "<a href=\""+url+"\">"+url+"</a>";
        //发送的邮箱内容
        String emailMsg = mailTemplate.getTemplate()
                .replace("{borrowBooksTime}",DateUtils.dateFormat("yyyy年MM月dd日",borrowBook.getBbTime()))
                .replace("{dueTime}",DateUtils.dateFormat("yyyy年MM月dd日",borrowBook.getDueTime()))
                .replace("{bookName}",borrowBook.getBName())
                .replace("{userName}",borrowBook.getRName())
                .replace("{remainingDay}",borrowBook.getRemainingDays()+"")
                .replace("{systemUrl}",aDocument);
        //发送邮箱提醒
        return "pages/manager/bookDatalist.jsp";
    }

    //读者自动登录
    @Transactional
    public Boolean autoLoginReader(HttpServletResponse response, HttpServletRequest request) {
        //获取账户名 (编码)
        String account = CookieUtils.getCookieValue(request, bmProperties.getAutoCookieName());
        if(StringUtils.isBlank(account)){ //空字符串  删除该cookie
            CookieUtils.deleteCookie(request,response, bmProperties.getAutoCookieName(),request.getContextPath()+ bmProperties.getCookiePath());   //用户端删除该cookie
            return false;
        }
        //查询账户是否存在
        List<Reader> readers = readerMapper.select(new Reader(account));
        if(CollectionUtils.isEmpty(readers)){   //未查询到 登录失败 用户账户不存在
            CookieUtils.deleteCookie(request,response, bmProperties.getAutoCookieName(),request.getContextPath()+ bmProperties.getCookiePath());   //用户端删除该cookie
            return false;
        }
        //将用户信息存入session中
        saveReaderToSession(request,readers.get(0));
        return true;
    }

    //将用户的信息保存到 session 中 并设置最后的登录时间
    private void saveReaderToSession(HttpServletRequest request,Reader reader){
        //将用户的登录信息保存到 session 中
        HttpSession session = request.getSession();
        session.setAttribute(bmProperties.getReaderSessionName(),reader);
    }
}

@Service
public class MailTemplateService {

    @Autowired
    @ResponseBody
    public ResponseEntity<Void> registerReader(@RequestBody Reader reader){
        reader.builderReader();
        readerService.saveReader(reader);
        return ResponseEntity.ok().build();
    }

    //发送邮箱验证码
    @PostMapping("/verifyMailCode/{account}/{email}")
    @ResponseBody
    public ResponseEntity<Void> verifyMailCode(@PathVariable("account") String account,
                                               @PathVariable("email") String email){
        readerService.verifyMailCode(account,email);
        return ResponseEntity.ok().build();
    }

}

public class UserLoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        System.out.println("UserLoginInterceptor");
        // 判断session
        HttpSession session  = request.getSession();
        // 从session中取出用户身份信息
        Reader userInfo = (Reader)session.getAttribute("readerInfo");
        // session存在时,放行
        if (userInfo!=null) {
            return true;
        }
        // 执行这里表示用户身份需要认证,跳转登陆页面
        response.sendRedirect("/pages/login.jsp");
        return false;
    }

}

@RequestMapping("manager/bookType")
@RestController
public class MBookTypeController {

    @Autowired
    private BookTypeService bookTypeService;

    //获取图书分类
    @RequestMapping
    public ResponseEntity<List<BookType>> bookTypeList(){
        return ResponseEntity.ok(bookTypeService.bookTypeList());
    }

    //获取图书分类
    @RequestMapping("/all")
    public ResponseEntity<List<BookType>> bookTypeListAll(){
        return ResponseEntity.ok(bookTypeService.bookTypeListAll());
    }

    //添加图书分类
    @PostMapping("/{tName}")
    public ResponseEntity<Void> addBookType(@PathVariable("tName") String tName){
        bookTypeService.addBookType(tName);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    //删除多个图书分类
    @DeleteMapping
    public ResponseEntity<Void> deleteBookTypes(@RequestBody List<Integer> ids ){
    }

    //修改图书
    @PutMapping
    public ResponseEntity<Void> modifyBook(@RequestBody Books books){
        bookService.modifyBook(books);
        return ResponseEntity.ok().build();
    }

    //修改图书的状态
    @PutMapping("/{bId}/{status}")
    public ResponseEntity<Void> modifyBookStatus(@PathVariable("bId") Integer bId,
                                                 @PathVariable("status") Boolean status){
        bookService.modifyBookStatus(bId,status);
        return ResponseEntity.ok().build();
    }

    //修改图书的总数量
    @PutMapping("/total/{bId}/{total}")
    public ResponseEntity<Void> modifyBookTotal(@PathVariable("bId") Integer bId,
                                                 @PathVariable("total") Integer total){
        bookService.modifyBookTotal(bId,total);
        return ResponseEntity.ok().build();
    }

//    //删除图书 多个
    @DeleteMapping
    public ResponseEntity<Void> deleteBookBybIds(@RequestBody List<Integer> ids){
        bookService.deleteBookBybIds(ids);
        return ResponseEntity.ok().build();
    }

    //删除图书 一个
    @DeleteMapping("/{bId}")
    public ResponseEntity<Void> deleteBookBybId(@PathVariable("bId") Integer bId){
        bookService.deleteBookBybIds(Arrays.asList(bId));
        return ResponseEntity.ok().build();
    }

}
		doSetCookie(request, response, cookieName, "", -1, false,path);
	}

	/**
	 * 设置Cookie的值,并使其在指定时间内生效
	 * 
	 * @param cookieMaxage
	 *            cookie生效的最大秒数
	 */
	private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, boolean isEncode,String path) {
		try {
			if (cookieValue == null) {
				cookieValue = "";
			} else if (isEncode) {
				cookieValue = URLEncoder.encode(cookieValue, "utf-8");
			}
			Cookie cookie = new Cookie(cookieName, cookieValue);
			if (cookieMaxage > 0)
				cookie.setMaxAge(cookieMaxage);
			if (null != request)// 设置域名的cookie
				cookie.setDomain(getDomainName(request));
			cookie.setPath(path);
			response.addCookie(cookie);
		} catch (Exception e) {
			logger.error("Cookie Encode Error.", e);
		}
	}

	/**
	 * 设置Cookie的值,并使其在指定时间内生效
	 * 
	 * @param cookieMaxage
	 *            cookie生效的最大秒数
	 */
	private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, String encodeString,String path) {
		try {
			if (cookieValue == null) {
				cookieValue = "";
			} else {
				cookieValue = URLEncoder.encode(cookieValue, encodeString);
			}
			Cookie cookie = new Cookie(cookieName, cookieValue);
			if (cookieMaxage > 0)
				cookie.setMaxAge(cookieMaxage);
			if (null != request)// 设置域名的cookie
				cookie.setDomain(getDomainName(request));
			cookie.setPath(path);
public class RGiveBackController {

    @Autowired
    private GiveBackBookService giveBackBookService;

    @Autowired
    private BMSystemProperties bmProperties;

    //分页查询 并可以带查询参数
    @GetMapping("/{page}/{size}")
    public ResponseEntity<Page<GiveBackBooks>> giveBackBook(@PathVariable("page") Integer page,
                                                            @PathVariable("size") Integer size,
                                                            GiveBackBooks reserveGiveBack,
                                                            HttpSession session){
        Reader reader = (Reader) session.getAttribute(bmProperties.getReaderSessionName());
        reserveGiveBack.setRName(reader.getRName());
        return ResponseEntity.ok(giveBackBookService.giveBackBook(page,size, reserveGiveBack,true));
    }

}

@RequestMapping("/reader/borrowBook")
@RestController
public class RBorrowBookController {
                .replace("{bookName}",borrowBook.getBName())
                .replace("{userName}",borrowBook.getRName())
                .replace("{remainingDay}",borrowBook.getRemainingDays()+"")
                .replace("{systemUrl}",aDocument);
        //发送邮箱提醒
        try {
            mailUtils.sendRemind(reader.getEmail(),emailMsg);
        } catch (MessagingException e) {    //发送邮箱还书提醒失败!
            e.printStackTrace();
            throw new LyException(ExceptionEnum.SEND_REMIND_FAIL);
        }
    }
}

@RequestMapping("reader/reserveBorrow")
@RestController
public class RReserveBorrowBooksController {

    @Autowired
    private ReserveBorrowBooksService reserveBookService;

    @Autowired
    private BMSystemProperties bmProperties;

    //分页查询 并可以带查询参数
    @GetMapping("/{page}/{size}")
    public ResponseEntity<Page<ReserveBorrowBooks>> borrowBookByPage(@PathVariable("page") Integer page,
                                                                     @PathVariable("size") Integer size,
                                                                     ReserveBorrowBooks reserveBorrowBooks,
                                                                     HttpServletRequest request){
        //获取当前用户
        Reader reader = (Reader)request.getSession().getAttribute(bmProperties.getReaderSessionName());
        reserveBorrowBooks.setRName(reader.getRName());  //根据当前用户查找
        return ResponseEntity.ok(reserveBookService.reserveBookByPage(page,size, reserveBorrowBooks));
        }
        MailTemplate mailTemplate = null;
        //实际借书天数(现在的时间-租借的时间)
        int readyDay =  DateUtils.differenceDay(new Date(),borrowBook.getBbTime());
        //最大借书天数 = 应该还书的时间-租借的时间
        int maxDay = DateUtils.differenceDay(borrowBook.getDueTime(),borrowBook.getBbTime());
        //逾期天数 = 实际借书天数 - 最大借书天数
        int overDay = readyDay - maxDay;
        //用户是否逾期
        if(overDay <=0 ){ //还未逾期
            //查询未逾期模板
            mailTemplate = templateMapper.selectByPrimaryKey(1);
            borrowBook.setRemainingDays(maxDay-readyDay);
        }else{
            mailTemplate = templateMapper.selectByPrimaryKey(2);
            borrowBook.setRemainingDays(overDay);
        }

        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
        String url = basePath;

        String aDocument = "<a href=\""+url+"\">"+url+"</a>";
        //发送的邮箱内容
        String emailMsg = mailTemplate.getTemplate()
                .replace("{borrowBooksTime}",DateUtils.dateFormat("yyyy年MM月dd日",borrowBook.getBbTime()))
                .replace("{dueTime}",DateUtils.dateFormat("yyyy年MM月dd日",borrowBook.getDueTime()))
                .replace("{bookName}",borrowBook.getBName())
                .replace("{userName}",borrowBook.getRName())
                .replace("{remainingDay}",borrowBook.getRemainingDays()+"")
                .replace("{systemUrl}",aDocument);
        //发送邮箱提醒
        try {
            mailUtils.sendRemind(reader.getEmail(),emailMsg);
        } catch (MessagingException e) {    //发送邮箱还书提醒失败!
            e.printStackTrace();
            throw new LyException(ExceptionEnum.SEND_REMIND_FAIL);
        }
    }
}


    }
}

@RequestMapping("register")
@RestController
public class RegisterController {

    @Autowired
    private ReaderService readerService;

    //用户名是否存在
    @PostMapping("/account/{accountName}")
    @ResponseBody
    public ResponseEntity<Void> accountName(@PathVariable("accountName") String accountName){
        readerService.accountNameExist(accountName);
        return ResponseEntity.ok().build();
    }

    //用户注册
    @PostMapping
    @ResponseBody
    public ResponseEntity<Void> registerReader(@RequestBody Reader reader){
        reader.builderReader();
        readerService.saveReader(reader);
        return ResponseEntity.ok().build();
    }

    //发送邮箱验证码
    @PostMapping("/verifyMailCode/{account}/{email}")
    @ResponseBody
    public ResponseEntity<Void> verifyMailCode(@PathVariable("account") String account,
                                               @PathVariable("email") String email){
        readerService.verifyMailCode(account,email);
        return ResponseEntity.ok().build();
    @PostMapping
    public ResponseEntity<Void> addBook(@RequestBody Books books){
        bookService.addBook(books);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    //修改图书
    @PutMapping
    public ResponseEntity<Void> modifyBook(@RequestBody Books books){
        bookService.modifyBook(books);
        return ResponseEntity.ok().build();
    }

    //修改图书的状态
    @PutMapping("/{bId}/{status}")
    public ResponseEntity<Void> modifyBookStatus(@PathVariable("bId") Integer bId,
                                                 @PathVariable("status") Boolean status){
        bookService.modifyBookStatus(bId,status);
        return ResponseEntity.ok().build();
    }

    //修改图书的总数量
    @PutMapping("/total/{bId}/{total}")
    public ResponseEntity<Void> modifyBookTotal(@PathVariable("bId") Integer bId,
                                                 @PathVariable("total") Integer total){
        bookService.modifyBookTotal(bId,total);
        return ResponseEntity.ok().build();
    }

//    //删除图书 多个
    @DeleteMapping
    public ResponseEntity<Void> deleteBookBybIds(@RequestBody List<Integer> ids){
        bookService.deleteBookBybIds(ids);
        return ResponseEntity.ok().build();
    }

    //删除图书 一个
    @DeleteMapping("/{bId}")
    public ResponseEntity<Void> deleteBookBybId(@PathVariable("bId") Integer bId){
        bookService.deleteBookBybIds(Arrays.asList(bId));
        return ResponseEntity.ok().build();
    }

}

            Map<String, String> params = getParams(request.getParameterMap());
            boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
            if (signVerified) {//验证成功
                //商户订单号
                String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
                //交易状态
                String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
                //交易金额
                Double total_amount = Double.parseDouble(new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8"));
                if (trade_status.equals("TRADE_FINISHED")) {
                } else if (trade_status.equals("TRADE_SUCCESS")) {
                   //获取订单信息
                    Map<String, String> map = jedis.hgetAll(out_trade_no);
                    if(!CollectionUtils.isEmpty(map)){  //订单未失效
                        if(map.get("status").equals("false")){   //订单未支付
                            //根据rId查询用户信息
                            Reader reader = readerMapper.selectByPrimaryKey(Integer.valueOf(map.get("rId")));
                            if(reader!=null){   //用户信息存在
                                //增加账户金额
                                reader.setBalance(reader.getBalance()+(int)(total_amount*100));
                                //持久化数据
                                readerMapper.updateByPrimaryKey(reader);
                                //设置订单已支付
                                map.replace("status","true");
                                //redis中设置订单已支付
                                jedis.hmset(out_trade_no,map);
                            }
                        }
                    }
                }
            } else {//验证失败
            }
        } catch (Exception e) {
            System.out.println(e);
            e.printStackTrace();
        }
    }

    //获取参数
    private Map<String, String> getParams(Map<String, String[]> requestParams){
        Map<String, String> params = new HashMap<String, String>();

@Service
public class LoginService {

    @Autowired
    private ReaderMapper readerMapper;

    @Autowired
    private ManagerMapper managerMapper;

    @Autowired
    private BMSystemProperties bmProperties;

    //用户登录
    public String login(LoginVo loginVo, HttpServletResponse response, HttpServletRequest request) {
        //判断用户的类型
        String type = loginVo.getType();
        String url;
        if(type.equals("读者")){
            url = loginReader(loginVo,response,request);
        }else{  //管理员
            url = loginManager(loginVo,request);
        }
        return url;
    }

    //用户登录
    @Transactional
    public String loginReader(LoginVo loginVo, HttpServletResponse response,HttpServletRequest request){
        //根据用户名和密码查询
        Example example = new Example(Reader.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("account",loginVo.getAccount())
                .andEqualTo("password",loginVo.getPassword());
        example.or().andEqualTo("email",loginVo.getAccount())
                .andEqualTo("password",loginVo.getPassword());
        List<Reader> readers = readerMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(readers)){   //不存在该用户,账号或密码错误!
            throw new LyException(ExceptionEnum.LOGIN_ACCOUNT_OR_PASSWORD);
        }
        //获取数据库中的读者信息
        Reader reader = readers.get(0);
        //判断是否有自动登录
        if(loginVo.getAutoLogin()){ //有自动登录
            Integer day = bmProperties.getReaderAutoLoginDay()*60*24;
            String path = request.getContextPath()+"/pages/reader/";
            //根据 账户名
            Cookie cookie = new Cookie(bmProperties.getAutoCookieName(),reader.getAccount());
            //设置路径
            cookie.setPath(path);

@Service
public class MailTemplateService {

    @Autowired
    private MailTemplateMapper templateMapper;

    @Autowired
    private BorrowBookMapper borrowBookMapper;

    @Autowired
    private ReaderMapper readerMapper;

    @Autowired
    private MailUtils mailUtils;

    @Autowired
    private HttpServletRequest request;

    public MailTemplate getMailTemplate(Integer id){
        return templateMapper.selectByPrimaryKey(id);
    }

    public void modifyMailTemplate(Integer id,String template) {
        templateMapper.updateByPrimaryKeySelective(new MailTemplate().setMtId(id).setTemplate(template));
    }

    public void modifyMailDefaultTemplate(Integer id, String defaultTemplate) {
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        //商户订单号,商户网站订单系统中唯一订单号,必填
        String orderNo = NumberUtils.getOrderNo();
        model.setOutTradeNo(orderNo);
        //订单名称,必填
        model.setSubject("图书借阅系统充值");
        //支付金额
        model.setTotalAmount(money+"");
        //超时关闭该订单时间
        model.setTimeoutExpress(bmProperties.getOrderZFBTimeoutExpress()+"m");
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        alipayRequest.setBizModel(model);
        //获取当前用户信息
        Reader reader = (Reader)request.getSession().getAttribute(bmProperties.getReaderSessionName());
        //redis中存入 订单编号 , 用户id,支付状态
        HashMap<String,String> map = new HashMap<>();
        map.put("rId",reader.getRId()+"");
        map.put("status","false");
        jedis.hmset(orderNo,map);
        //redis中支付订单失效时间
        Integer time = (bmProperties.getZFBTimeoutExpressAddTime()+bmProperties.getOrderZFBTimeoutExpress())*60;
        jedis.expire(orderNo,time);
        //请求
        try {
            String result  = alipayClient.pageExecute(alipayRequest).getBody();
            //输出
            response.getWriter().println(result);
        } catch (Exception e) {
            System.out.println("支付请求失败");
            e.printStackTrace();
        }
    }

    //同步通知
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public void returnUrl(HttpServletRequest request) {
        try{
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
    public Reader queryById(Integer rId) {
        return readerMapper.selectByPrimaryKey(rId);
    }

    //判断账户名是否存在
    public void accountNameExist(String accountName) {
        if (!CollectionUtils.isEmpty(readerMapper.select(new Reader(accountName)))) {    //账户名已存在
            throw new LyException(ExceptionEnum.READER_ACCOUNT_NAME_EXIST);
        }
    }

    //用户注册
    public void saveReader(Reader reader) {
        //根据用户的账户名获取邮箱的验证码
        String verifyCode = jedis.get(reader.getAccount());
        if (StringUtils.isBlank(verifyCode)) {    //验证码已失效,或邮箱地址错误!
            throw new LyException(ExceptionEnum.VERIFY_EXPIRY_OR_EMAIL_ERROR);
        }
        if (!reader.getVerifyCode().equals(verifyCode)) { //邮箱验证码不匹配
            throw new LyException(ExceptionEnum.VERIFY_CODE_NOT_MATCHING);
        }
        reader.builderReader();
        readerMapper.insert(reader);
    }

    //发送邮箱验证码
    public void verifyMailCode(String account, String email) {
        //获取4位数的验证码
        String verifyCode = new Random().nextInt(9999) + "";
        //将验证码根据 account存入redis中
        jedis.set(account, verifyCode);
        //设置验证码有效期
        jedis.expire(account, bmProperties.getEmailVerifyCodeMinute()*60);
        //发送邮箱验证码
        Integer validMinute = bmProperties.getEmailVerifyCodeMinute();
        String emailMsg = bmProperties.getMailReaderRegisterContentModel();
        emailMsg = emailMsg.replace("{emailVerifyCode}", verifyCode).replace("{emailVerifyCodeMinute}", validMinute + "");
        try {
            mailUtils.sendRegisterVerifyCode(email, emailMsg);
        } catch (MessagingException e) {

请添加图片描述

请添加图片描述
请添加图片描述
请添加图片描述
请添加图片描述
请添加图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值