public class RandomCodeServlet extends HttpServlet{
private int width = 60;//验证码的宽度
private int height = 20;//验证码的高度
protected void service(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{
BufferedImage buffImg = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
Graphics2D g = buffImg.createGraphics();
//产生Random
Random random = new Random();
g.setColor(Color.WHITE);
g.fillRect(0,0,width,height);
//字体
Font font = new Font("Dialog",Font.PLAIN,18);
g.setFont(font);
//边框
g.setColor(Color.BLACK);
g.drawRect(0,0,width-1,height-1);
//产生160条干扰线,图像中的认证码,不被看到
g.setColor(Color.GRAY);
for(int i=0;i<160;i++){
int x = random.nextInt(width);
int y = random.nextInt(height);
int x1 = random.nextInt(12);
int y1 = random.nextInt(12);
g.drawLine(x,y,x1,y1);
}
StringBuffer randomCode = new StringBuffer();//保存验证码
int red = 0,green = 0,blue = 0;
for(int i = 0;i < 4;i++){
String strRand=String.valueOf(random.nextInt(10));
//Color
red = random.nextInt(110);
green = random.nextInt(50);
blue = random.nextInt(50);
//set Color
g.setColor(new Color(red,green,blue));
g.drawString(strRand,13*i+6,16);
randomCode.append(strRand);//保存验证码
}
//搞验证码 到SESSION中去
HttpSession session=req.getSession();
session.setAttribute("randdomCode",randomCode.toString());