java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
{
//此方法生成一张图片
Random r=new Random();
//1.创建空白图片
BufferedImage image=new BufferedImage(100,30,BufferedImage.TYPE_INT_RGB);
//2.获取图片的画笔
Graphics g=image.getGraphics();
//3.设置画笔的颜色
g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.next(255)));
//4.绘制矩形的背景
g.fillRect(0,0,100,30);
//5.调用自定义的方法,获取长度为5的字母和数字的字符串
String number=this.getNumber(5);
//6.把随机生存的验证码存储在session中
HttpSession session=request.getSession();
session.setAttribute("code",number);
//7.重新设置画笔,准备画验证码
g.setColor(new Color(0,0,0));
g,setFont(new Font(null,Font.BOLD,24));
//8.绘制验证码
g.drawString(number,5,25);
//9.绘制8条干扰线
for(int i=0;i<8;i++){
g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255),));
g.drawLine(r.nextInt(100),r.nextInt(30),r.nextInt(100),r.nextInt(30));
}
//10.设置响应的内容
response.setContentType("image/jpeg");
OutputStream os=response.getOutputStream();
//11.把image图片写出到响应中(写到网络输出流上)
ImageIO.write(image,"jpeg",os);
os.flush();
os.close();
}
private String getNumber(int size){
String str="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
String number="";
Random r=new Random();
for(int i=0;i<size;i++){
number+=str.charAt(r.nextInt(str.length()));
}
return number;
}