Java Web学习笔记(九) 登陆注册页面验证码的实现

实训第六天学习笔记
验证码可以有效防止机器恶意注册、登陆、暴力破解密码。

画页面
<!-- 用的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值比较。

实现效果

在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Chook_lxk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值