Servlet生成随机验证码

今天复习servlet时,看到自己写的一个简单的登录界面用到了验证码,于是就想把验证码制作这块整理一下,方便以后使用,同时也希望各位大牛能提出更好的改进方法。废话不多说,上代码!

package com.hefan;


import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
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;


public class createCode extends HttpServlet {
/**
* This is my modified template
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
//设置浏览器禁止缓存
response.setDateHeader("Expires",-1);
response.setHeader("Cache-Control","no-cache");
response.setHeader("Pragma", "no-cache");
//设置响应文档的内容类型为jpeg类型,
//从而告知浏览器这是一个图片类型
response.setHeader("Content-Type","image/jpeg");
//在内存中创建一副图片,长:80,高:30
BufferedImage image = new BufferedImage(80, 30, BufferedImage.TYPE_INT_RGB);
//得到图片的画笔
Graphics g = image.getGraphics();
//设置背景颜色
g.setColor(Color.WHITE);
//设置背景矩形的大小
g.fillRect(0, 0, 80, 30);
//设置20条随机的干扰线
  getInterferenceLine(g,20);
//设置字体颜色
g.setColor(Color.BLACK);
//设置字体类型
g.setFont(new Font(null, Font.BOLD,20));
//得到随机验证码
String num = makeNum();
//将验证码保存在Session中
request.getSession().setAttribute("checkCode", num);
//将产生的随机验证码画在图片上
g.drawString(num, 0, 20);
//图片生效
g.dispose(); 
//输出图片到页面
ImageIO.write(image, "jpeg", response.getOutputStream());
}
//产生随机验证码
public String makeNum(){
Random r = new Random();
String num = r.nextInt(9999999)+"";
StringBuffer sb = new StringBuffer();
for(int i=0;i<7-num.length();i++){
sb.append("0");
}
num = sb.toString() + num;
return num;
}
//产生干扰线
public void getInterferenceLine(Graphics g,int num){
    for (int i = 0; i < num; i++) {
   //获取随机的颜色
             g.setColor(generateColor());
             //产生每条干扰线的两个顶点
             int x1 = (int) (Math.random() * 80);
             int y1 = (int) (Math.random() * 30);
             int x2 = (int) (Math.random() * 80);
             int y2 = (int) (Math.random() * 30);
             //画出干扰线
             g.drawLine(x1, y1, x2, y2);
        }
}
//产生随机颜色
public Color generateColor() {
         int r = (int) (Math.random() * 180);
         int g = (int) (Math.random() * 180);
         int b = (int) (Math.random() * 180);
         return new Color(r, g, b);
  }
/**
* This is my modified template
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}

你可能感兴趣的:(Servlet生成随机验证码)