javaweb实现验证码功能

在系统登录或者注册时,为防止有人恶意注册账号或者尝试暴力破解用户密码,常需要使用验证码来验证用户是否是人为操作。

 话不多说,直接上代码:

public class yzm extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public yzm() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 设置浏览器不缓存
		response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        //设置响应类型
		response.setContentType("image/jpeg");
		//定义图片宽高
		int width = 60;
		int height = 20;
		//创建一个缓冲区图片
		BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		//使用缓冲区图片创建 图形对象以用于绘制验证码
		Graphics g = img.getGraphics();
		//设置画笔颜色为黄色,后续画矩阵,相当于设置图形背景颜色为黄色
		g.setColor(new Color(255, 255, 0));
		g.fillRect(0, 0, width, height);
		//设置字体
		g.setFont(new Font("微软雅黑", Font.ITALIC, 18));
		//定义空字符串,以便后续连接
		String srand = "";
		Random random = new Random();
		for (int i = 0; i < 4; i++) {
			String rand = String.valueOf(random.nextInt(10));
			srand += rand;
			//随机更换颜色,以便验证码数字颜色多样
			g.setColor(new Color(30 + random.nextInt(160), 50 + random.nextInt(100), 80 + random.nextInt(140)));
			//将随机数画入图形
			g.drawString(rand, i*16, 18);
		}
		//随机生成30条线条
		for (int i = 0; i < 30; i++) {
			int x=random.nextInt(width);
			int y=random.nextInt(height);
			int x1=random.nextInt(10);
			int y1=random.nextInt(10);
			g.drawLine(x, y, x+x1, y+y1);
		}
		//在session中设置连接好的验证码字符串
		request.getSession().setAttribute("yzm", srand);
		//释放 图形资源
		g.dispose();
		//将图片写入到response输出流
		ImageIO.write(img, "jpeg", response.getOutputStream());
		
	}

接下来可在jsp中验证:

<body>
	<form action="index.jsp">
		<input type="text" name="yzm"> <img alt="" src="yzm"> <input
			type="submit">
	</form>
	<%
		if (request.getParameter("yzm") != null) {
			if (request.getParameter("yzm").toString().equals(session.getAttribute("yzm").toString()))
				out.print("<script>alert('succeed!')</script>");
		}
	%>
</body>

运行效果:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值