简介
在实现登录功能时,一般为了安全都会设置验证码登录,为了防止某个用户用特定的程序暴力破解方式进行不断的尝试登录。常见验证码分为图片验证码和短信验证码,还有滑动窗口模块和选中指定物体验证方式。下面通过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

最低0.47元/天 解锁文章
5793

被折叠的 条评论
为什么被折叠?



