34、验证码

学习目标:

1、了解验证码的作用

2、掌握验证码的实现

学习过程:

一、为什么需要验证码

1、什么是验证码

相信大家经常上网都会见到验证码的,如下图:

你可以随便打开一个有验证码的网站看看,那到底什么是验证码呢?验证码上面的数字或者字母是随机生成的,验证其实就是一副动态生成的图片。用户需要输入和验证码生成的图片内容一致的内容才可能继续操作。

2、验证码有什么作用呢

事实上验证码对用户体验非常不好,那为什么很多网站还是需要使用验证码呢?其实验证码的真正作用是为了保护服务器的,因为本身http协议可以允许用户不断访问网站的,对一些安全性比较好或者需要修改数据库内容的功能,用户是可以很轻松就可以对其攻击了,比如登录功能,如果不使用验证码,那么很有可能有一些黑客对其进行密码的暴力破解,如果是注册等操作有可能会有人通过程序批量的添加数据,这样你的数据库很快就会蹦贵。验证码就是解决这些复杂问题的最简单方式,目前还没有比验证码更好的解决方式,所有很多网站还是会使用验证码。比如下面这段代码就可以批量的注册用户了。

	public static void main(String[] args) {

		for (int i = 0; i < 100000; i++) {
			String weburl = "http://localhost:8080/userdem/admin/userServlet?op=add&username=liubao&sex=1";

			try {
				URL url = new URL(weburl);
				URLConnection connection = url.openConnection();
				BufferedReader br = new BufferedReader(new InputStreamReader(
						connection.getInputStream()));

				String line = br.readLine();
				while (line != null) {
					System.out.println(line);
					line = br.readLine();
				}
				br.close();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

二、实现验证

1、生成验证码

那么我们如何可以实现验证码?事实验证码非常简单,就是在服务器中随机生成四个字母或者数字,保存在session中,并生成一副图片,发给浏览器显示即可。

(1)新建一个servlet,用于生成验证码图片,同时把验证码字符串保存在session中。

public class ValidateServlet extends HttpServlet {

	// 验证吗图片的宽度
	private int width = 200;;
	// 高度
	private int height = 80;

	// 验证吗的字符个数
	private int codeCount = 4;

	private int x = 0;
	// 字体高度
	private int fontHeight;
	private 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' };

	@Override
	public void init() throws ServletException {

		super.init();
	}

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

		// 创建一个随机数生成器类
		Random random = new Random();

		// 1、生成一幅图片。
		x = width / (codeCount + 1);
		fontHeight = height - 2;
		codeY = height - 4;
		// 定义图像buffer
		BufferedImage buffImg = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		Graphics2D g = buffImg.createGraphics();

		// 将图像填充为白色
		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 < 160; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			g.drawLine(x, y, x + xl, y + yl);
		}

		// 2、生产随机数
		// randomCode用于保存随机产生的验证码,以便用户登录后进行验证。
		StringBuffer randomCode = new StringBuffer();
		int red = 0, green = 0, blue = 0;
		// 随机产生codeCount数字的验证码。
		for (int i = 0; i < codeCount; i++) {
			// 得到随机产生的验证码数字。
			String strRand = String.valueOf(codeSequence[random.nextInt(36)]);
			// 产生随机的颜色分量来构造颜色值,这样输出的每位数字的颜色值都将不同。
			red = random.nextInt(255);
			green = random.nextInt(255);
			blue = random.nextInt(255);

			// 用随机产生的颜色将验证码绘制到图像中。
			g.setColor(new Color(red, green, blue));
			g.drawString(strRand, (i + 1) * x-30, codeY);

			// 将产生的四个随机数组合在一起。
			randomCode.append(strRand);
		}

		// 3、要把随机数放在session中
		// 将四位数字的验证码保存到Session中。
		HttpSession session = request.getSession();
		session.setAttribute("validateCode", randomCode.toString());

		// 4、输出图片

		// 禁止图像缓存。
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);

		response.setContentType("image/jpeg");

		// 将图像输出到Servlet输出流中。
		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(buffImg, "jpeg", out);

		out.flush();

		out.close();

	}

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

	}

}

(2)servlet在web.xml的配置如下:

	<servlet>
    <servlet-name>ValidateServlet</servlet-name>
    <servlet-class>com.servlet.ValidateServlet</servlet-class>
  </servlet>

	<servlet-mapping>
		<servlet-name>ValidateServlet</servlet-name>
		<url-pattern>/validateServlet</url-pattern>
	</servlet-mapping>

(3)在登录页面中使用,就是使用img控件,src指向这个servlet路径就可以了

 
	<form action="loginServlert" method="post">
		用户名:<input name="username"  value="liubao" /> <br /> 密码:<input name="pass" value="123" 
			type="password" /> <br /> 
			
			验证码:<input  name="vcode"/> <img alt="" id="imgcode" src="validateServlet" onclick="updatecode()" style="cursor: pointer;" >
			
			 <br /> 
			 
			<input type="submit" value="登录" />
	</form>

2、验证码的验证功能

用户输入的验证码和保存session验证比较,如果相同,才进行数据库的操作,我们应该在登录判断之前完成

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		HttpSession session=request.getSession();
		
		//先判断用户输入的验证码是否正确
		String sessionCode=session.getAttribute("validateCode").toString();
		String userCode=request.getParameter("vcode");
		
		System.out.println(sessionCode+":"+userCode);
		
		if(!sessionCode.equalsIgnoreCase(userCode)){
			//session.setAttribute("error", "验证码错误");
			response.sendRedirect("index.jsp?error=cerror");
			return;
		}
		
       
		UserDao userDao=new UserDao();
		
		String username=request.getParameter("username");
		String pass=request.getParameter("pass");
		
		User user=userDao.login(username, pass);
		
		if(user!=null){
			//session.removeAttribute("error");
			request.getSession().setAttribute("user", user);
			
			response.sendRedirect("admin/userServlet?op=list");
		}else{
			//session.setAttribute("error", "用户名密码错误");
			response.sendRedirect("index.jsp?error=uerror");
		}
		
		
	}

三、优化界面显示

这样我们的验证码就实现了,下面我们在优化一下界面,用户如果看不清验证还可以换一张试一试的,这个功能使用js就可以完成了。


<script type="text/javascript">
   
   function updatecode(){
      var imgcode=document.getElementById("imgcode");
      imgcode.src="validateServlet?abc="+new Date();
   }

</script>

猜你喜欢

转载自blog.csdn.net/liubao616311/article/details/84072088