在spring MVC下简单的验证码源码。
@Controller // 注解问控制器
@RequestMapping("/login") // 访问路径
public class GetCodeController {
@RequestMapping("/getCode")
public void execute(HttpServletResponse response,
HttpSession session)throws Exception {
BufferedImage image = new BufferedImage(100, 30,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random r = new Random();
g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
g.fillRect(0, 0, 100, 30);
String number = getNumber(5);
session.setAttribute("scode", number);
g.setColor(new Color(0, 0, 0));
g.setFont(new Font(null, Font.BOLD, 24));
g.drawString(number, 5, 25);
for (int i = 0; i < 8; i++) {
g.setColor(new Color(r.nextInt(255), r.nextInt(255),
-
r.nextInt(255), r.nextInt(255)));
g.drawLine(r.nextInt(100), r.nextInt(30),r.nextInt(100), r.nextInt(30));
} response.setContentType("image/jpeg"); OutputStream ops = response.getOutputStream(); ImageIO.write(image, "jpeg", ops); ops.close(); }private String getNumber(int size) {
String str =
-
"ABCDEFGHIJKLMNOPQRSTUVWXYZqwertyuiopasdfghjklzxcvnm0123456789";
String number = ""; Random r = new Random(); for (int i = 0; i < size; i++) { number += str.charAt(r.nextInt(str.length())); } return number; }}
验证码是我们在web开发中经常要用的的一个组件,特别是在请求分发中利用控制器
来获取验证码,便于维护而且高大上。
本文出自 “你是ITer为bug而活” 博客,请务必保留此出处http://king2.blog.51cto.com/8746235/1591190