jsp+servlet实现验证码功能

验证码的功能大多数人可能不都理解,但几乎每个安全网站都会有。验证码是用来防止非人为因素操作的行为,例如一个黑客要黑一个网站,怎么弄呢?最简单的思路当然是造成其网路拥堵直至系统瘫痪掉。如果没有验证码,那么我就可以在注册页面,写一个程序,只有注册表单,不断更换主键或不可重复的内容,不停的提交。那这样每秒可以注册几万次都有可能,这样服务器就大量负载,很容易就瘫痪并死掉。而达到这样的目的并不困难。

增加验证码之后,就不是机器人能识别的了,必须是人在操作系统,由于是图片形式的,而且歪歪斜斜乱七八糟,而现阶段图形模式识别技术还没做到能够识别验证码的程度,所以加上验证码就相对安全了很多。在软件开发中难免会遇到这样的情况,客户压根不知道验证码用来干什么的,但一定要加不可。为什么要加?因为大家都有。没法子总要加上才显得自己专业,其实这个东西很容易加,就是用数字或字母做模板用swing的图形API,画出一个图片出来。完整的逻辑和代码如下:

<img id="validateCodeId" src="validateCodeServlet"
                                    onclick="flushValidateCode(this);" title='看不清,点击刷新'
                                    style="cursor: pointer;" />

//刷新验证码
flushValidateCode = function(obj) {
	obj.src  ='validateCodeServlet?d='+new Date();
}

请求的URL是validateCodeServlet,后面参数d=new Date()是保证每次点击刷新的时候URL都不一样,否则会不刷新。别的地方也使用Math.rand();这样的办法取得一个随机数,这样也是可以的。

web.xml这样来配置servlet的映射信息。

  <servlet>
    <servlet-name>validateCode</servlet-name>
    <servlet-class>com.xzfy.mainpage.web.action.ValidateCodeServlet</servlet-class>
  </servlet>
    <servlet-mapping>
        <servlet-name>validateCode</servlet-name>
        <url-pattern>/validateCodeServlet</url-pattern>
    </servlet-mapping>
ValidateCodeServlet

package com.xzfy.mainpage.web.action;

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

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

import org.apache.commons.io.output.ByteArrayOutputStream;

public class ValidateCodeServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public ValidateCodeServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("image/jpeg");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		HttpSession session = request.getSession();

		int width = 60, height = 20;
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);

		Graphics g = image.getGraphics();

		Random random = new Random();

		g.setColor(getRandColor(200, 250));
		g.fillRect(0, 0, width, height);

		g.setFont(new Font("Times New Roman", Font.PLAIN, 18));

		g.setColor(getRandColor(160, 200));
		for (int i = 0; i < 155; 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);
		}

		String sRand = "";
		for (int i = 0; i < 4; i++) {
			String rand = String.valueOf(random.nextInt(10));
			sRand += rand;
			g.setColor(new Color(20 + random.nextInt(110), 20 + random
					.nextInt(110), 20 + random.nextInt(110)));// 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
			g.drawString(rand, 13 * i + 6, 16);
		}
		session.setAttribute("rand", sRand);
		g.dispose();
		ServletOutputStream responseOutputStream = response.getOutputStream();
		ImageIO.write(image, "JPEG", responseOutputStream);

		responseOutputStream.flush();
		responseOutputStream.close();
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request, response);
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}
	Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
		
		
	}
}

效果如下:


作者:xinfei0803 发表于2012-12-27 14:41:02 原文链接
阅读:0 评论:0 查看评论

你可能感兴趣的:(jsp,servlet,验证码)