这篇文章主要为大家详细介绍了Java实现图片验证码功能,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
简介
在实现登录功能时,一般为了安全都会设置验证码登录,为了防止某个用户用特定的程序暴力破解方式进行不断的尝试登录。常见验证码分为图片验证码和短信验证码,还有滑动窗口模块和选中指定物体验证方式。下面通过Java来实现图片验证码实例。
效果展示
如上图所示,图片验证码由4个数字和一些彩色的干扰线段组成,点击图片可以更新验证码,只有输入的验证码与图片中的数字一致才能通过登录,否则将会重新刷新验证码,重新输入正确的验证码。
示例代码
1、controller
@RestController
public class ValidateCodeController {
@GetMapping("/getCodeImg")
public void getCodeImage(HttpServletRequest request, HttpServletResponse response, HttpSession httpSession) throws IOException, InterruptedException {
BufferedImage image=new BufferedImage(80, 32, BufferedImage.TYPE_3BYTE_BGR);
//编辑图像
//获取绘图对象
Graphics g=image.getGraphics();
g.setColor(new Color(239, 239, 239));
g.fillRect(0,0,80,32);
//设置字体颜色
g.setColor(new Color(49, 49, 49));
//设置字体
g.setFont(new Font("SimSong",Font.ITALIC,20));
//绘制字符串;
String text="";
for(int i=0;i<4;i++) {
text +=(int) (Math.random()*10);
}
//字符串输出内容,水平起始坐标,垂直起始坐标。
g.drawString(text, 17, 24);
//画线条
for (int i = 0; i < 10; i++) {
g.setColor(new Color((int) (Math.random()*255), (int) (Math.random()*255), (int) (Math.random()*255)));
g.drawLine((int) (Math.random()*50),(int) (Math.random()*30),(int) (Math.random()*80),(int) (Math.random()*80));
}
//设置session
httpSession.setAttribute("code",text);
//输出图像
//ImageIO.write(image, "png", new FileOutputStream("C:/Users/H/Desktop/"+tet+".png"));
ImageIO.write(image, "png",response.getOutputStream());
g.dispose();
}
//获取保存在session中的验证码
@GetMapping("/getCode")
public String getCode(HttpSession httpSession){
return (String) httpSession.getAttribute("code");
}
}
2、登录页面
<body>
<div class="layui-container" id="container">
<!--登录-->
<div class="login" id="login">
<h3 class="header">登 陆</h3>
<span style="color: red;font-weight: 800">{{msg}}</span>
<form class="layui-form loginForm" th:action="@{
织梦狗教程
本文标题为:Java实现图片验证码功能


基础教程推荐
猜你喜欢
- Java使用EasyExcel进行单元格合并的问题详解 2023-01-18
- Project Reactor源码解析publishOn使用示例 2023-04-12
- JVM分析之类加载机制详解 2023-04-06
- 用java实现扫雷游戏 2022-12-06
- SpringBoot配置文件中密码属性加密的实现 2023-03-11
- 全局记录Feign的请求和响应日志方式 2023-01-09
- Java File类的概述及常用方法使用详解 2023-05-18
- 一文了解Java 线程池的正确使用姿势 2023-06-17
- Java去掉小数点后面无效0的方案与建议 2023-02-18
- 工厂方法在Spring框架中的运用 2023-06-23