在spring MVC下简单的验证码源码。web
@Controller // 注解问控制器spring
@RequestMapping("/login") // 访问路径session
public class GetCodeController {app
@RequestMapping("/getCode")dom
public void execute(HttpServletResponse response, ide
HttpSession session)throws Exception {ui
BufferedImage p_w_picpath = new BufferedImage(100, 30,BufferedImage.TYPE_INT_RGB);spa
Graphics g = p_w_picpath.getGraphics();code
Random r = new Random();
ci
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("p_w_picpath/jpeg"); OutputStream ops = response.getOutputStream(); ImageIO.write(p_w_picpath, "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开发中常常要用的的一个组件,特别是在请求分发中利用控制器
来获取验证码,便于维护并且高大上。