欢迎光临
这是我的个人博客

java web绘制验证码springMVC

在前端创建验证码 会出现安全问题,所以验证码就在后台绘制,然后发送到后台,这样就会变得安全的很多。因此就有了以下教程,复制即可使用。

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;

@RequestMapping(value = "/getCode")
	public void yaz(HttpServletResponse response, HttpServletRequest request,HttpSession session) throws Exception {
		request.setCharacterEncoding("UTF-8");
		response.setHeader("Pragma", "No-cache");  
	    response.setHeader("Cache-Control", "No-cache");  
	    response.setDateHeader("Expires", 0);
		response.setCharacterEncoding("text/html;charset=utf-8");

		int width = 80;
		int height = 40;

		// 画板

		BufferedImage b = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

		// 工具

		Graphics g = b.getGraphics();

		g.setColor(new Color(40, 200, 255));

		g.fillRect(0, 0, width, height);

		char[] ch = "QWERTYUIOPASDFGHJKLZXCVBNM1234567890".toCharArray();

		Random random = new Random();

		int len = ch.length, index;

		StringBuffer sb = new StringBuffer();

		for (int i = 0; i < 4; i++) {

			index = random.nextInt(len);

			g.setColor(new Color(random.nextInt(88), random.nextInt(188), random.nextInt(255)));

			g.setFont(new Font("微软雅黑", Font.BOLD, 18));

			g.drawString(ch[index] + "", i * 15 + 3, 18);

			sb.append(ch[index]);

		}
		System.out.println("验证码为;"+sb.toString());
		// 干扰线
		session.setAttribute("CHECKCODE", sb.toString());//可以将验证码放到session中,然后实现校验功能
		for (int i = 1; i < 10000; i++) {

			g.setColor(new Color(random.nextInt(88), random.nextInt(188), random.nextInt(255)));

			g.drawLine(random.nextInt(i * 3 + 2), random.nextInt(i * 5 + 1), random.nextInt(i * 3 + 1), random.nextInt(i * 9));

		}

		// 结束

		g.dispose();

		b.flush();

		// 保存

		request.getSession().setAttribute("yzm", sb.toString());

		try {

			// 输出图片到页面

			ImageIO.write(b, "png", response.getOutputStream());

		} catch (IOException e) {

		}
	

}

HTML代码

<img alt="" src="<%=request.getContextPath()%>/admin/getCode" onclick="reload()">
<script type="text/javascript">
function reload(){
var time = new Date().getTime();
document.getElementById("reload").src="<%=request.getContextPath()%>/getCode?d="+time;
}

</script>

这样刷新一下就可以获得验证码,在做校验的时候直接在session中获取验证码即可,服务器会自动区别请求来自那里。

赞(0) 打赏
未经允许不得转载:好好网 » java web绘制验证码springMVC

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏