验证码的实现有很多种方法,可以通过导入有关验证码的jar包直接调用其方法创建,也可以自己手动创建一个验证码类.
有关生成验证码的jar包网上有很多,实现方式不一,这里我对第一种实现方式就不多做介绍.
接下来就带着大家自己手动创建一个验证码类.
代码实现:
package test.captcha;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 生成验证码
* @author striner
*
*/
public class Captcha extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width = 110;
int height = 25;
//在内存中创建一个图像对象
BufferedImage img = new BufferedImage(width, heigh