java编写一个简单的验证码
public class ImageServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setHeader("refresh","3"); //在内存中创建一个画布 BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB); //得到画笔 Graphics2D g = (Graphics2D) image.getGraphics(); //设置画笔颜色 g.setColor(Color.white); //画一个填充矩形 g.fillRect(0,0,80,20); //写数据 g.setColor(Color.BLUE); g.setFont(new Font(null,Font.BOLD,20)); g.drawString(makeNum(),0,20); //告诉浏览器文件类型 resp.setContentType("image/jpg"); //网站有缓存,要清除缓存 resp.setDateHeader("expires",-1); resp.setHeader("Cache-Control","no-cache"); resp.setHeader("Pragma","no-cache"); //把图片写给浏览器 ImageIO.write(image,"jpg", resp.getOutputStream()); } public String makeNum(){ Random random = new Random(); // 100000--999999 String i = random.nextInt((999999-100000)+1)+100000+""; return i; } }