Java后端产生验证码后台验证功能的实现代码

这篇文章主要介绍了Java后台产生验证码后台验证功能,本文文字结合实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下

直接跳severlet在java后台生成验证码:

 @RequestMapping(value="yzm.action") public void Yzm(HttpSession session,HttpServletResponse resp){ // 验证码图片的宽度。 int width = 60; // 验证码图片的高度。 int height = 20; // 验证码字符个数 int codeCount = 4; int x = 0; // 字体高度 int fontHeight; int codeY; char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; x = width / (codeCount + 1); fontHeight = height - 2; codeY = height - 4; BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g = buffImg.createGraphics(); // 创建一个随机数生成器类 Random random = new Random(); // 将图像填充为白色 g.setColor(Color.WHITE); g.fillRect(0, 0, width, height); // 创建字体,字体的大小应该根据图片的高度来定。 Font font = new Font("Fixedsys", Font.PLAIN, fontHeight); // 设置字体。 g.setFont(font); // 画边框。 //    g.setColor(Color.BLACK); //    g.drawRect(0, 0, width - 1, height - 1); // 随机产生160条干扰线,使图象中的认证码不易被其它程序探测到。 g.setColor(Color.BLACK); for (int i = 0; i <1; i++) { int x2 = random.nextInt(width); int y2 = random.nextInt(height); int xl = random.nextInt(12); int yl = random.nextInt(12); g.drawLine(x2, y2, x + xl, y2 + yl); } // randomCode用于保存随机产生的验证码,以便用户登录后进行验证。 StringBuffer randomCode = new StringBuffer(); int red = 0, green = 0, blue = 0; // 随机产生codeCount数字的验证码。 for (int i = 0; i 

jsp显示页面的代码,点击图片刷新

 ${validateCode}
$("#img").click(function(){ $(this).attr("src","yzm.action?"+new Date().getTime()); });

将文本框中的值传入后台,与最开始生成验证码的随机数进行比较即可完成验证。

页面上拿到的session的值老是比验证码晚一步,所以采取后台进行验证。这里我也不知道什么原因,望小伙伴们告知。。。

另一种思路,后台生成随机数,前端生成画布,用ajax拿随机数

 //后台只生成随机数 @RequestMapping(value="random.action") public void findRandom (HttpServletResponse response) throws IOException{ // 验证码字符个数 int codeCount = 4; char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; // 创建一个随机数生成器类 Random random = new Random(); // randomCode用于保存随机产生的验证码,以便用户登录后进行验证。 StringBuffer randomCode = new StringBuffer(); for (int i = 0; i 

 jsp,jq,js代码

  换一张