jsp圖形驗證碼

圖形驗證碼Servlet實現

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

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

/**
 * Servlet implementation class CheckCodeServlet
 */
@WebServlet("/CheckCodeServlet")
public class CheckCodeServlet extends HttpServlet {
	public static final String CHECKCODE = "checkCode";// 放到session中的key
	private Random random = new Random();
	private static String CHECKCODES = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";// 隨機產生的字符串

	private static int WIDTH= 60;// 圖片寬
	private static int HEIGHT = 20;// 圖片高

	private static final long serialVersionUID = 1L;
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession();
		response.setContentType("image/jpeg");
		ServletOutputStream sos=response.getOutputStream();
		//設置圖片不緩存
		response.setHeader("progma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		// BufferedImage類是具有緩衝區的Image類,Image類是用於描述圖像信息的類
		BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
				BufferedImage.TYPE_INT_RGB);
		// 產生Image對象的Graphics對象,改對象可以在圖像上進行各種繪製操作
		Graphics g = image.getGraphics();
		char[] code=this.generateCheckCode();
		this.drawBackground(g);
		this.drowString(g, code);
		g.dispose();
		ByteArrayOutputStream bos=new ByteArrayOutputStream();
		ImageIO.write(image, "jpeg", bos);
		byte[] buf=bos.toByteArray();
		response.setContentLength(buf.length);
		sos.write(buf);
		bos.close();
		sos.close();
		session.setAttribute(CHECKCODE, new String(code));
		
	}


	/*
	 * 繪製字符串
	 */
	private void drowString(Graphics g, char[] code) {
		g.setColor(Color.BLACK);
		g.setFont(new Font(null,Font.ITALIC|Font.BOLD,18));
		
		
		g.drawString(""+code[0], 1, 17);
		g.drawString(""+code[1], 16, 15);
		g.drawString(""+code[2], 31, 18);
		g.drawString(""+code[3], 46, 16);
	}
	
	/*
	 * 繪製干擾點
	 */
	private void drawBackground(Graphics g){
		//畫背景
		g.setColor(new Color(0xDCDCDC));
		g.fillRect(0, 0, WIDTH, HEIGHT);
		//隨機產生干擾點
		for(int i=0;i<120;i++){
			int x=(int)(Math.random()*WIDTH);
			int y=(int)(Math.random()*HEIGHT);
			int red=(int)(Math.random()*255);
			int blue=(int)(Math.random()*255);
			int green=(int)(Math.random()*255);
			g.setColor(new Color(red,green,blue));
			g.drawOval(x, y, 1, 0);
		}
	}
	
	/*
	 * 獲取隨機的字符
	 */
	private char[] generateCheckCode() {
		char code[]=new char[4];
		for(int i=0;i<4;i++)
		{
			int n=(int)(Math.random()*62);
			code[i]=CHECKCODES.charAt(n);
		}
		return code;
	}

}

測試頁面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="" method="post">
<table>
	<tr>
		<td>name:</td>
		<td><input type="text" id="name"/></td></tr>
	<tr>
		<td>SN:</td>
		<td><input type="password" id="psw"></td></tr>
	<tr>
		<td><input type="submit" value="submit"></td>
		<td><img src="getCheckCode"></td></tr>
</table>
</form>
</body>
</html>

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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
  <display-name></display-name>
  <servlet>
    <servlet-name>checkCode</servlet-name>
    <servlet-class>com.control.CheckCodeServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>checkCode</servlet-name>
    <url-pattern>/getCheckCode</url-pattern>
  </servlet-mapping>
</web-app>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章