图例如下
具体操作如下:
新建一个servlet,代码如下:标记一个WebServlet,
1 @WebServlet(urlPatterns = {"/checkCode"}) //验证码Servlet
绘制验证码图片的核心代码:
int width = 100; int height = 50; //创建图片对象 BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); //美化图片 Graphics g = image.getGraphics(); //1:填充背景 g.setColor(Color.pink); g.fillRect(0, 0, width, height); //画边框 g.setColor(Color.blue); g.drawRect(0, 0, width - 1, height - 1); //生成一个验证码字符串 String strCheckCode = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; Random random = new Random(); StrCheckCode = ""; for (int i = 1; i <= 4; i++) { int index = random.nextInt(strCheckCode.length()); char ch = strCheckCode.charAt(index); StrCheckCode += ch;//拼接验证码 g.drawString(ch + "", width / 5 * i, height / 2); } //画干扰线 for (int i = 0; i < 5; i++) { int x1 = random.nextInt(width); int x2 = random.nextInt(width); int y1 = random.nextInt(height); int y2 = random.nextInt(height); g.drawLine(x1, x2, y1, y2); } //输出,显示出来 ImageIO.write(image, "jpg", resp.getOutputStream()); }