1 import java.awt.Color; 2 import java.awt.Font; 3 import java.awt.Graphics2D; 4 import java.awt.image.BufferedImage; 5 import java.io.IOException; 6 import java.util.ArrayList; 7 import java.util.List; 8 import java.util.Random; 9 10 import javax.imageio.ImageIO; 11 import javax.servlet.ServletException; 12 import javax.servlet.ServletOutputStream; 13 import javax.servlet.annotation.WebServlet; 14 import javax.servlet.http.HttpServlet; 15 import javax.servlet.http.HttpServletRequest; 16 import javax.servlet.http.HttpServletResponse; 17 import javax.servlet.http.HttpSession; 18 19 @WebServlet("/validcode") 20 public class ValidCodeServlet extends HttpServlet { 21 @Override 22 protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 23 //创建一张图片 24 //单位:像素 25 BufferedImage image = new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB); 26 27 //透明的玻璃 28 //向画板上画内容之前必须先设置画笔. 29 Graphics2D gra = image.createGraphics(); 30 31 gra.setColor(Color.WHITE); 32 //从哪个坐标开始填充, 后两个参数,矩形区域 33 gra.fillRect(0, 0, 200, 100); 34 35 List<Integer> randList = new ArrayList<Integer>(); 36 Random random =new Random(); 37 for (int i = 0 ;i<4;i++) { 38 randList.add(random.nextInt(10)); 39 } 40 //设置字体 41 gra.setFont(new Font("宋体",Font.ITALIC|Font.BOLD,40)); 42 Color[] colors = new Color[]{Color.RED,Color.YELLOW,Color.BLUE,Color.GREEN,Color.PINK,Color.GRAY}; 43 for (int i = 0; i < randList.size(); i++) { 44 gra.setColor(colors[random.nextInt(colors.length)]); 45 gra.drawString(randList.get(i)+"", i*40, 70+(random.nextInt(21)-10)); 46 } 47 48 for (int i = 0; i < 2; i++) { 49 gra.setColor(colors[random.nextInt(colors.length)]); 50 //画横线 51 gra.drawLine(0, random.nextInt(101), 200, random.nextInt(101)); 52 } 53 54 ServletOutputStream outputStream = resp.getOutputStream(); 55 //工具类 56 ImageIO.write(image, "jpg", outputStream); 57 58 //把验证码放入到session中 59 HttpSession session = req.getSession(); 60 session.setAttribute("code", ""+randList.get(0)+randList.get(1)+randList.get(2)+randList.get(3)); 61 } 62 }