web验证码的生成以及验证

应用场景:在登录的网页常常要用到验证码,能有效的防止恶意的登陆注册,暴力的提交数据

验证码是一张图片,java有专门绘制图的类Graphics。

验证码小demo下载地址:http://download.csdn.net/download/bushqiang/10260194

例子演示:
1.jsp页面用一个img标签来放验证码

<img src="verifyCodeImage" id="verifyCodeImage" onclick="javascript:myRefersh();">

2.script提交换图请求,要导入jquery

<script>
	$(function() {
		myRefersh();
	});
	function myRefersh() {
		var date = new Date(); // 创建一个 Date 对象的 一个 实例  
		var time = date.getTime(); // 从 新创建的 Date 对象的实例中获得该时间对应毫秒值  
		$('#verifyCodeImage').attr('src', 'verifyCodeImage?time=' + time);
	}
</script>

verifyCodeImage的请求后面加上时间戳time是因为换验证码是局部的刷新,浏览器有记忆功能,会自己缓存已经请求过的页面,为了表示不同于之前的验证码,所以用时间来区别。

3.后台处理接收到请求后就画一个验证码,再传给前台。

	//生成验证码
	@RequestMapping("/verifyCodeImage")
	public ModelAndView regist(HttpServletRequest request,HttpServletResponse response) throws Exception{	
		// 获得 当前请求 对应的 会话对象  
	   HttpSession session = request.getSession();  
	    final int width = 120; // 图片宽度  
	    final int height = 40; // 图片高度  
	    final String imgType = "jpeg"; // 指定图片格式 (不是指MIME类型)  
	    final OutputStream output = response.getOutputStream(); // 获得可以向客户端返回图片的输出流  
	   // 创建验证码图片并返回图片上的字符串  
	    String codeimage = GraphicHelper.create(width, height, imgType, output);
	   //存放验证码
	    session.setAttribute("codeimage", codeimage);
	    output.flush();
	    output.close();
		return null;
	}


4.画验证码的类

public final class GraphicHelper {

	/**
	 * 以字符串形式返回生成的验证码,同时输出一个图片
	 * 
	 * @param width
	 *            图片的宽度
	 * @param height
	 *            图片的高度
	 * @param imgType
	 *            图片的类型
	 * @param output
	 *            图片的输出流(图片将输出到这个流中)
	 * @return 返回所生成的验证码(字符串)
	 */
	public static String create(final int width, final int height,
			final String imgType, OutputStream output) {
		StringBuffer sb = new StringBuffer();
		Random random = new Random();

		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		Graphics graphic = image.getGraphics();
		graphic.setColor(Color.getColor("F8F8F8"));
		graphic.fillRect(0, 0, width, height);

		Color[] colors = new Color[] { Color.BLUE, Color.GRAY, Color.GREEN,
				Color.RED, Color.BLACK, Color.ORANGE, Color.magenta,Color.darkGray,Color.pink };
		// 在 "画板"上生成干扰线条 ( 40 是线条个数)
		for (int i = 0; i < 40; i++) {
			graphic.setColor(colors[random.nextInt(colors.length)]);
			final int x = random.nextInt(width);
			final int y = random.nextInt(height);
			final int w = random.nextInt(20); 
			final int h = random.nextInt(20);
			final int signA = random.nextBoolean() ? 1 : -1;
			final int signB = random.nextBoolean() ? 1 : -1;
			graphic.drawLine(x, y, x + w * signA, y + h * signB);
		}

		// 在 "画板"上绘制字母
		graphic.setFont(new Font("Comic Sans MS", Font.BOLD, 30));
		for (int i = 0; i < 4; i++) {
			final int temp = random.nextInt(26) + 97;
			String s = String.valueOf((char) temp);
			sb.append(s);
			graphic.setColor(colors[random.nextInt(colors.length)]);
			graphic.drawString(s, i * (width / 4), height - (height / 3));
		}
		graphic.dispose();
		try {
			ImageIO.write(image, imgType, output);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
}
5.校验验证码是否正确

// 用户登录处理
	@RequestMapping("/userlogin")
	public ModelAndView checklogin(HttpSession session,
			HttpServletRequest request) throws Exception {
		ModelAndView modelAndView = new ModelAndView();
		//获取验证码
		String verifyCode = request.getParameter("verifyCode");
		String code = (String) session.getAttribute("codeimage");
		//验证码错误
		if(!code.equals(verifyCode.toLowerCase())){
			modelAndView.addObject("message", str + "验证码错误!");
			modelAndView.addObject("user", user);
			// 返回首页,并且提示错误
			modelAndView.setViewName("index");
			return modelAndView;
		}else{
                     //登陆成功就清除验证码的session
            session.removeAttribute("codeimage");//防止用户重复提交表单
                }
        }

6.验证码效果图,上面的小demo是项目的一部分和下面的效果图有一点小差距,按照我上面代码修改就可以了



猜你喜欢

转载自blog.csdn.net/bushqiang/article/details/79380871