动态生成验证码

public class ImageServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置当前页面的文档类型,默认text/html
        resp.setContentType("image/gif");
        //申请了一块画布
        BufferedImage bufferedImage = new BufferedImage(50,20,BufferedImage.TYPE_INT_RGB);
        //得到一个画笔,设置背景颜色为白色
        Graphics graphics = bufferedImage.getGraphics();
        graphics.setColor(Color.white);
        graphics.fillRect(0, 0, 50, 20);
        graphics.setColor(Color.red);
        //生成验证码,随机颜色以及数字字母
        String number = "";
        for (int i = 0; i < 4; i++) {
            graphics.setColor(getRandomColor());
            String code = getRandomChar();
            number+=code;
            graphics.drawString(code, 10 + (i * 10), 12);
        }
        //生成五条随机的干扰线
        for (int i = 0; i < 5; i++) {
            graphics.setColor(getRandomColor());
            graphics.drawLine(new Random().nextInt(50), new Random().nextInt(20), new Random().nextInt(50), new Random().nextInt(20));
        }
        //响应给浏览器
        ImageIO.write(bufferedImage, "jpg", resp.getOutputStream());
    }
    //生成随机颜色
    public Color getRandomColor(){
        return new Color(new Random().nextInt(255), new Random().nextInt(255), new Random().nextInt(255));
    }
    //所有的数字字母,存入list集合
    public String getRandomChar(){
        ArrayList list = new ArrayList();
        for (int i = 0; i < 10; i++) {
            list.add(i);
        }
        for (int i = 65; i < 65+26; i++) {
            list.add((char)i);
        }
        for (int i = 97; i < 97+26; i++) {
            list.add((char)i);
        }
        return list.get(new Random().nextInt(list.size()))+"";
    }
}