欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 文化 > Java生成图形验证码

Java生成图形验证码

2024/10/24 19:29:09 来源:https://blog.csdn.net/heming20122012/article/details/141136484  浏览:    关键词:Java生成图形验证码

1、加依赖

<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.16</version></dependency>

2、写接口,这块不需要登录成功才能操作的,所以写controller就行了,不涉及服务

package com.hmblogs.backend.controller;import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.hmblogs.backend.config.CaptchaProperties;
import com.hmblogs.backend.util.JedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;@RestController
@RequestMapping("/captcha")
public class CaptchaController {@Autowiredprivate CaptchaProperties captchaProp;@RequestMapping("/get")public void getCaptcha(HttpServletRequest request, HttpServletResponse response, HttpSession session) {// 定义图形验证码的长和宽(配置默认值)LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProp.getWidth(), captchaProp.getHeight());// 细节问题,不影响程序// 设置返回类型response.setContentType("image/jpeg");// 静止缓存response.setHeader("Progma", "No-cache");try {// 图形验证码写出,可以写出到文件,也可以写出到流lineCaptcha.write(response.getOutputStream());// 这里是缓存图形验证码逻辑,也可以放库里,或者session里,但要用用户名区别,因为还没登录所以不要使用用户ID区别// 在相关功能(例如登录)的时候,要对应验证判断一下Jedis jedis = JedisUtil.getJedisConn();String username = request.getParameter("username");jedis.setex("imageToken:"+username,2*60, lineCaptcha.getCode());// 关流response.getOutputStream().close();} catch (IOException e) {throw new RuntimeException(e);}}}

3、对应的配置文件

package com.hmblogs.backend.config;import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;@Data
@Configuration
@ConfigurationProperties(prefix = "captcha")
public class CaptchaProperties {private Integer width;private Integer height;
}

4、对应的配置文件的配置

captcha:width: 200height: 100

5、开发页面,使用的是vue的ref来控制页面图形验证码区域显示,点击图片区域则会换一个图形验证码

6、验证

页面加载时,有调用该接口

查看redis的缓存,和页面看到的一致

点击图形区域,发现又调用了该接口

查看redis缓存

验证完毕。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com