1. 程式人生 > >生成驗證碼並在頁面進行顯示

生成驗證碼並在頁面進行顯示

 

code.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>code.html</title>
	
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="this is my page">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
    <script type="text/javascript" src="js/jquery.js"></script>
    <script type="text/javascript">
    	$(function() {
    		
    		init();
    	
    		$("[type='button']").click(function() {
    			$.post("servlet/CheckCode",{},function(data) {
    				//注意這裡src的寫法,data是經過base64編碼後的內容
    				$("img").attr("src","data:image/jpeg;base64,"+data);
    			});
    		});
    		
    	});
    	function init() {
    		$.post("servlet/CheckCode",{},function(data) {
    			//其實在第一次執行的時候是可以直接將圖片的二進位制作為Image的src進行顯示的,但是因為後臺統一返回的是
    			//經過base64編碼過後的內容,所以這裡初始顯示的時候也是利用base64的方法
   				$("img").attr("src","data:image/jpeg;base64,"+data);
   			});
    	}
    </script>

  </head>
  
  <body>
    <img alt="" width=100 >
    <input type="button" value="換一張"/>
  </body>
</html>

Servlet:

mport java.io.IOException;
import java.util.Random;

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

import sun.misc.BASE64Encoder;

import com.tiantian.ext.util.Util;

public class CheckCode extends HttpServlet {

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

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//直接返回位元組流給img標籤的src是可以的,如<img src="servlet/CheckCode">,但在之後進行切換的時候
		//使用ajax請求,如果僅僅返回圖片的二進位制然後把它傳給img的src是不能的,目前的方法是把圖片的二進位制進行base64編碼,
		//然後在頁面上以下列方式進行顯示,<img src="data:image/jpeg;base64,result">,其中的result是經過
		//base64編碼後的內容,這樣就可以使用後臺直接利用圖片的二進位制進行圖片的顯示了
		response.setContentType("image/jpeg;charset=utf-8");
		response.addHeader("pragma", "no-cache");  
		response.addHeader("Cache-Control", "no-cache");
		StringBuffer buffer = new StringBuffer();
		for (int i=0;i<4;i++)
			buffer.append(new Random().nextInt(9));
		String code = buffer.toString();
		byte[] bytes = Util.geneCheckCode(code).toByteArray();
		BASE64Encoder encoder = new BASE64Encoder();
		//使用base64進行轉碼,否則在頁面不能直接顯示,至少目前我還沒有發現方法,可以直接將圖片的位元組流使用ajax的方法在頁面
		//上進行顯示
		String result = encoder.encode(bytes);
		response.getWriter().write(result);
	}

}

Util類:

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.Properties;
import java.util.Random;

import javax.imageio.ImageIO;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;

public class Util {

	private static DefaultKaptcha kaptcha = new DefaultKaptcha();
	//初始化Kaptcha
	static {
		kaptcha.setConfig(new Config(new Properties()));
	}
	
	/**
	 * 利用kaptcha的實現
	 * @param code
	 * @return
	 * @throws IOException
	 */
	public static ByteArrayOutputStream geneCheckCode(String code) throws IOException {
		BufferedImage bufferedImage = kaptcha.createImage(code);
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ImageIO.write(bufferedImage, "jpg", out);
		return out;
	}
	
	/**
	 * 自己的實現
	 * @param text
	 * @return
	 * @throws IOException
	 */
	public static ByteArrayOutputStream gene(String text) throws IOException {
		char chars[] = text.toCharArray();
		BufferedImage image = new BufferedImage(200, 50, BufferedImage.TYPE_INT_BGR);
		Graphics graphics = image.getGraphics();
		graphics.setColor(Color.red);
		
		for (int i=0;i<chars.length;i++) {
			graphics.setFont(new Font("宋體", Font.BOLD, 35+new Random().nextInt(10)));
			graphics.drawChars(new char[] {chars[i]}, 0, 1, 45*i+10, 40);
		}
		graphics.setColor(new Color(255, 200, 200));
		for (int i=0;i<17;i++) {
			graphics.drawLine(i*12, 0, i*12, 50);
			graphics.drawLine(0, i*3, 200, i*3);
		}
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ImageIO.write(image, "jpg", out);
		return out;
	}
	
}