springboot旅游项目实战记录

本文详细介绍了在前后端分离架构下,如何通过生成并保存唯一时间戳和验证码至session,再利用base64编码实现图片验证码的获取和展示。文章探讨了如何克服前后端分离时无法直接访问session的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 前后端分离获取验证码问题
@GetMapping("/getImage")
    @ResponseBody
    public Map<String, String> getImage(HttpServletRequest request) throws IOException {
        Map<String, String> result = new HashMap<>();
        CreateImageCode createImageCode = new CreateImageCode();
        // 获取验证码
        String securityCode = createImageCode.getCode();
        // 验证码存入session,前后端分离不能获取session中的验证码,  创建唯一时间戳
        String key = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        // 使用session获取最大作用域,将唯一时间戳为key和验证码为值存入
        request.getServletContext().setAttribute(key, securityCode);
        // 生成图片
        BufferedImage image = createImageCode.getBuffImg();
        //进行base64编码, 创建byte流数组,将图片写入其中
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", bos);
        //进行base64编码, 将内存中的字节编码成 base64的字符串
        String string = Base64Utils.encodeToString(bos.toByteArray());
        // 设置到result集合中返回
        result.put("key", key);
        result.put("image", string);
        return result;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值