使用servlet编写生成验证码

来源:互联网 发布:网络平台是干什么的 编辑:程序博客网 时间:2024/06/05 16:48

使用servelt编写的生成随机的验证码:

public class VerificationCode extends HttpServlet {
     public static final int WIDTH = 120;
     public static final int HEIGHT = 25;

 @Override
 protected void service(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
      BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
      BufferedImage.TYPE_INT_RGB);
    Graphics g = image.getGraphics();

      // 设置背景
      setBackGround(g);

      // 设置边框
      setBorder(g);

      // 画干扰线
      drawRandowLine(g);
      // 写随机数
      drawRandowNum((Graphics2D)g);
      // 图形写给浏览器
      response.setContentType("image/jpeg");

      //设置刷新之后是新生成的图片
      response.setDateHeader("expries", -1);
      response.setHeader("Cache-Control","no-cache");
      response.setHeader("Pragma", "no-cache");
  ImageIO.write(image, "jpg", response.getOutputStream());
 }
             //画随机数
            private void drawRandowNum(Graphics2D g) {
             //设置显示出来字体的颜色
           g.setColor(Color.RED);
         //字体样式
         g.setFont(new Font( "隶书",Font.BOLD,20));
       //定义需要显示的验证码
  String base="abcdefghijklmnopqrstuvwxyz";
       int x=5;
  for (int i = 0; i < 4; i++) {
       int degree=new Random().nextInt()%30;
       String ch=base.charAt(new Random().nextInt(base.length()))+"";
       //设置旋转角度
       g.rotate(degree*Math.PI/180,x,20);
       g.drawString(ch, x, 20);
       //设置反方向的角度
       g.rotate(-degree*Math.PI/180,x,20);
       x+=30;
  }
 }
                //画干扰线
 private void drawRandowLine(Graphics g) {
  g.setColor(Color.CYAN);
  for (int i = 0; i < 20; i++) {
   int x1=new Random().nextInt(WIDTH);
   int y1=new Random().nextInt(HEIGHT);
   int x2=new Random().nextInt(WIDTH);
   int y2=new Random().nextInt(HEIGHT);
   g.drawLine(x1, y1, x2, y2);
  }
 }
           //设置边框的颜色
 private void setBorder(Graphics g) {
            g.setColor(Color.MAGENTA);
           g.drawRect(1, 1, WIDTH-2, HEIGHT-2);
 }
             //设置背景色
 private void setBackGround(Graphics g) {
             g.setColor(Color.WHITE);
            g.fillRect(0, 0, WIDTH, HEIGHT);
 }
}

在web.xml中配置一下:

在浏览器中访问一下:

一个简单的生成验证码的程序就编写好了

编写JSP页面

最后实际效果: