登录验证码的制作与判断正误

需要使用的文件:
reg.html页面文件
验证码制作文件ImageServlet.java
提交响应文件RegServlet
web.xml配置文件

这句话<img src="ImageServlet" />,我们在web.xml文件里面配置ImageServlet文件,可以直接通过这个src访问到ImageServlet文件,然后获得回应,显示验证码
reg.html文件---------------------------------------------

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h2>用户注册</h2>
	<form action="RegServlet" method="POST">
		帐号:<input type="text" id="userName" name="userName" onblur="sendRequest()" />
		<div id="msg"></div>
		<br /> 验证码<input type="text" name="validate" />
		<img src="ImageServlet" /> <br /> <input type="submit" value="提交" />
	</form>
</body>
</html>

------------------------------------------------------------------------
验证码制作文件ImageServlet.java
---------------------------------------------------------------

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

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ImageServlet extends HttpServlet {

	// 定义可选择的字符
	private static final String CHARS = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
	static Random random = new Random();

	// 得到一个随机的字符串
	private String getRandomString() {
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < 6; i++) { // 生成六个字符
			buffer.append(CHARS.charAt(random.nextInt(CHARS.length())));
		}
		return buffer.toString();
	}

	// 随机背景颜色
	public static Color getRandomColor() { // 得到随机颜色
		return new Color(random.nextInt(128) + 127, random.nextInt(128) + 127,
				random.nextInt(128) + 127);
	}

	public static Color getReverseColor(Color c) { // 得到颜色的反色
		return new Color(255 - c.getRed(), 255 - c.getGreen(),
				255 - c.getBlue());
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("image/jpeg"); // 设置输出类型

		// 得到随机字符串
		String randomString = getRandomString();
		// 将getSession()设置为true,当会话不存在是返回null
		//将验证码存入session对象,方便验证的时候取出
		request.getSession(true).setAttribute("randomString", randomString);
		// 设置图片的宽、高
		int width = 80;
		int height = 30;

		Color bcolor = getRandomColor(); // 设置背景色
		Color fcolor = getReverseColor(bcolor); // 前景色

		// 创建一个彩色图片
		BufferedImage bimage = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_BGR);
		// 创建绘图对象,从bimage上得到的绘制对象,会把数据绘制到bimage上
		Graphics2D g = bimage.createGraphics();
		// 字体样式为宋体,加粗,20磅
		g.setFont(new Font("Vijaya", Font.BOLD, 20));
		// 先画出背景色
		g.setColor(bcolor);
		g.fillRect(0, 0, width, height);

		// 再画出前景色
		g.setColor(fcolor);
		for (int i = 0; i < randomString.length(); i++) {
			// 绘制随机字符
			g.drawString(randomString.charAt(i) + "", 10 + i * 12, 22);
		}

		// 画出干扰点
		for (int i = 0, n = random.nextInt(100); i < n; i++) {
			g.fillRect(random.nextInt(width), random.nextInt(height), 1, 1);
		}
//上面部分便是生成验证码图片代码,下面是将图片输出到请求对象浏览器页面

		// 将图像输出到浏览器
		ServletOutputStream outstream = response.getOutputStream();
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outstream);
		encoder.encode(bimage);
		outstream.flush();
		outstream.close();
	}
}

 ----------------------------------------------
接下来是提交验证码后判断对错的文件响应文件RegServlet

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RegServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//首先判断验证码
		//获得用户提交的验证码
		String validate = request.getParameter("validate");
		//从session中获得系统生成的验证码
		String randomStr = (String)request.getSession().getAttribute("randomString");
		
		if(validate.equalsIgnoreCase(randomStr)){
			
			//当验证码正确的时候,才来获得其他数据
			System.out.println("验证码正确!!");
		}else{
			System.out.println("验证码错误!!");
			
		}		
	}
}

 
-web.xml配置文件------------------------------------------------------------------------

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>PicValidate</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>ImageServlet</servlet-name>
    <servlet-class>servlet.ImageServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>ImageServlet</servlet-name>
    <url-pattern>/ImageServlet</url-pattern>
  </servlet-mapping>
  
  <servlet>
    <servlet-name>RegServlet</servlet-name>
    <servlet-class>servlet.RegServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>RegServlet</servlet-name>
    <url-pattern>/RegServlet</url-pattern>
  </servlet-mapping>
 
</web-app>

  

相关推荐