`
太阳神喻
  • 浏览: 105518 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

JSP图片验证码

    博客分类:
  • JSP
阅读更多

产生图片验证码的Servlet:

package web;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ValidationCode extends HttpServlet {

	/**
	 * 验证码的字符集合。
	 */
	private static String codeChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	
	/**
	 * 产生随机的颜色
	 * @param minColor
	 * @param maxColor
	 * @return
	 */
	private static Color getRandomColor(int minColor,int maxColor)
	{
		Random r = new Random();
		int red = minColor + r.nextInt(maxColor-minColor);
		int green = minColor + r.nextInt(maxColor-minColor);
		int blue = minColor + r.nextInt(maxColor-minColor);		
		return new Color(red,green,blue);
	}
	
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//关闭客户端浏览器的缓冲区。
		response.setHeader("ragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Expirse", "0");
		//设置图形大小。
		int width = 90 , height = 20;
		//建立图形缓冲区。
		BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();//获得	Graphics 对象。	
		g.setColor(getRandomColor(180, 250));//设置背景色。
		g.fillRect(0, 0, width, height);//填充背景。
		
		StringBuilder validationCode = new StringBuilder();//用于保存最后的验证码
		String[] fontNames = {"Times New Roman","Book antiqua","Arial"};//用于随机的字体的集合
		
		Random r = new Random();
		//随机生成3-5个验证码
		for(int i = 0; i<3+r.nextInt(3); i++)
		{
			g.setFont(new Font(fontNames[r.nextInt(3)] , Font.ITALIC , height));
			char codeChar = codeChars.charAt(r.nextInt(codeChars.length()));
			validationCode.append(codeChar);			
			g.setColor(getRandomColor(10, 100));
			g.drawString(String.valueOf(codeChar), 16 * i+ r.nextInt(7) ,height - r.nextInt(6));//在图形上输出验证码
		}
		//随机生干扰码
		for(int i = 0; i<30 ; i++)
		{
			g.setColor(getRandomColor(90, 200));
			int x = r.nextInt(width);
			int y = r.nextInt(height);
			g.drawLine(x,y , x+r.nextInt(10), y+r.nextInt(5));
		}
		
		HttpSession session = request.getSession();//得到HttpSession对象
		session.setMaxInactiveInterval(10*60);//设置session对象10分钟失效。
		session.setAttribute("validation_code", validationCode.toString());//将验证码保存在session中
		g.dispose();//关闭Graphics对象
		OutputStream os = response.getOutputStream();//得到输出流
		ImageIO.write(image, "JPEG", os);//以JPEG格式向客户端发送图形验证码
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

}

 

检测验证码是否正确的方法:

/**
	 * 核对用户输入的验证码是否合法
	 * 
	 * @param request
	 * @param validationCode
	 * @return
	 */
	private boolean checkValidationCode(HttpServletRequest request,String validationCode) {
		// 从HttpSession中获得系统随机生成的验证码
		String validationCodeSession = (String) request.getSession().getAttribute("validation_code");
		// 如果获得的验证码为null,说明难码过期,必须刷新客户端重新获取
		if (validationCodeSession == null) {
			request.setAttribute("info", "验证码过期");
			return false;
		}
		// 输入的验证码不匹配
		if (!validationCode.equalsIgnoreCase(validationCodeSession)) {
			request.setAttribute("info", "验证码不正确!");
			return false;
		}
		return true;
	}

 

JSP页面:使用图形验证码的方法非常简单,只需将“validationCode”(产生验证码的Servlet的url-pattern)作为<img>标签的src属性值即可

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
	<title>注册</title>
	<script type="text/javascript">
		//重新获得验证码
		function refresh() {
			var img = document.getElementById("img_code");
			img.src = "validationCode?" + Math.random();//加随机参数,以保证每次的src属性都不同
		}
	</script>
</head>

	<body>
		<form action="register" method="post">
			<center>
				用 户 名:
				<input type="text" name="userName">
				<br />
				密 码:
				<input type="password" name="pwd">
				<br />
				确认密码:
				<input type="password" name="pwd2">
				<br />
				邮 箱:
				<input type="text" name="email">
				<br />
				验 证 码:
				<input type="text" name="validation_code">
				<img title="单击刷新" alt="验证码" src="validationCode" id="img_code" onclick="refresh()">
				<br />
				<input type="submit" value="注册">
				<input type="reset" value="重置">
			</center>
		</form>
	</body>
</html>

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics