Servlet-SrpingMVC 生成验证码

 

 

在SpringMVC中配置生成验证码:

 

 1 import org.springframework.stereotype.Controller;
 2 import org.springframework.web.bind.annotation.RequestMapping;
 3 
 4 
 5 import java.awt.Color;
 6 import java.awt.Graphics;
 7 import java.awt.image.BufferedImage;
 8 import java.io.IOException;
 9 import java.io.PrintWriter;
10 import java.util.Random;
11 
12 import javax.imageio.ImageIO;
13 import javax.servlet.ServletException;
14 import javax.servlet.http.HttpServletRequest;
15 import javax.servlet.http.HttpServletResponse;
16 
17 @Controller
18 public class RegisterController {
19     
20     
21     // 图片高度
22     private static final int IMG_HEIGHT = 100;
23     // 图片宽度
24     private static final int IMG_WIDTH = 30;
25     // 验证码长度
26     private static final int CODE_LEN = 4;
27     
28     @RequestMapping(value = "/getCode.action")
29     public void getCode(HttpServletRequest req, HttpServletResponse resp)
30             throws ServletException, IOException {
31         // 用于绘制图片,设置图片的长宽和图片类型(RGB)
32         BufferedImage bi = new BufferedImage(IMG_HEIGHT, IMG_WIDTH, BufferedImage.TYPE_INT_RGB);
33         // 获取绘图工具
34         Graphics graphics = bi.getGraphics();
35         graphics.setColor(new Color(100, 230, 200)); // 使用RGB设置背景颜色
36         graphics.fillRect(0, 0, 100, 30); // 填充矩形区域
37 
38         // 验证码中所使用到的字符
39         char[] codeChar = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456".toCharArray();
40         String captcha = ""; // 存放生成的验证码
41         Random random = new Random();
42         for(int i = 0; i < CODE_LEN; i++) { // 循环将每个验证码字符绘制到图片上
43             int index = random.nextInt(codeChar.length);
44             // 随机生成验证码颜色
45             graphics.setColor(new Color(random.nextInt(150), random.nextInt(200), random.nextInt(255)));
46             // 将一个字符绘制到图片上,并制定位置(设置x,y坐标)
47             graphics.drawString(codeChar[index] + "", (i * 20) + 15, 20);
48             captcha += codeChar[index];
49         }
50         // 将生成的验证码code放入sessoin中
51         req.getSession().setAttribute("code", captcha);
52         
53         //设置响应头部
54         response.setContentType("image/jpeg");
55 
56         // 通过ImageIO将图片输出
57         ImageIO.write(bi, "JPG", resp.getOutputStream());
58         
59     }
60 
61 }

 

posted @ 2018-07-12 15:58  爱喝可乐的咖啡  阅读(147)  评论(0编辑  收藏  举报