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 @   爱喝可乐的咖啡  阅读(147)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示