版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/l1832876815/article/details/86583908
实训第六天学习笔记
验证码可以有效防止机器恶意注册、登陆、暴力破解密码。
画页面
<!-- 用的layui的框架画的页面-->
<!-- src是Java端获取验证码的方法 后面加随机数因为有些浏览器相同的src请求不执行-->
<div class="layui-inline veri-code">
<div class="layui-input-inline">
<input id="vertif" type="text" name="vertif"
lay-verify="required" placeholder="验证码" autocomplete="off"
class="layui-input">
<img src="/market/commen/authCode" class="layui-btn"
id="vet" onclick="this.src='/market/commen/authCode?'+Math.random();" />
<div id="check" style="color: red; font-size: 12px"></div>
</div>
</div>
方法
/*
*response以字节流的形式传到前端
*/
@Controller
@RequestMapping("commen")
public class AuthCodeController {
@RequestMapping("authCode")
public void authCode(HttpServletResponse response, HttpSession session) throws IOException {
BufferedImage image = FormatAuthCode.getAuthCode(4, 85, 30, session);
ImageIO.write(image, "jpg", response.getOutputStream());
}
}
public class FormatAuthCode {
//显示的字符范围
private static char[] chs = "0123456789qwertyuiopasdfghjklzxcvbnm".toCharArray();
//count为显示字符的个数,width和height为验证码的宽高,session为了保存验证码之后比较
public static BufferedImage getAuthCode(int count, int width, int height, HttpSession session) {
if(count < 1 || width < 1 || height < 1 || session == null) {
return null;
}
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g = image.createGraphics();//2d画板
g.setColor(new Color(238, 238, 238));//画板背景
g.fillRect(0, 0, width, height);//画板左上角坐标及宽高
g.setFont(new Font("Times New Roman", Font.BOLD, 25));//画板字体样式
StringBuffer code = new StringBuffer();
Random random = new Random();
//count次加载随机数
for(int i = 0; i < count; i++) {
int index = random.nextInt(chs.length);
g.setColor(new Color(random.nextInt(255), random.nextInt(255), random.nextInt(255)));
g.drawString(String.valueOf(chs[index]), 20 * i + 5, 23);
code.append(chs[index]);
}
session.setAttribute("authCode", code.toString());
return image;
}
}
之后可以通过ajax将前端的输入与Java端session值比较。