1.Controller package com.ryx.action;
import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.util.Random;
import javax.imageio.ImageIO; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping;
@Controller @RequestMapping("/images") public class PicController { private int width = 120; private int height = 40; private String source = "123456789";
@RequestMapping("pic")
public void showPic(HttpSession session, HttpServletResponse resp) throws Exception {
BufferedImage buffer = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
Graphics g = buffer.getGraphics();
g.setColor(Color.ORANGE);
g.fillRect(0, 0, width, height);
g.setColor(Color.BLACK);
g.drawRect(2, 2, width - 6, height - 6);
String checkcode = this.generateCheckcode(4);
session.setAttribute("checkcode", checkcode);
g.setFont(new Font("宋体", Font.BOLD, 28));
g.setColor(new Color(158, 50, 75));
g.drawString(checkcode, 10, height - 10);
// 注意实际上这里还需要绘制杂点或者线,以避免使用OCR识别图片
g.dispose();
// 清除缓存
resp.setHeader("pragma", "no-cache");
resp.setHeader("cache-control", "no-cache");
resp.setDateHeader("expires", -1);
// 说明打开图片类型
resp.setContentType("image/jpeg");
resp.resetBuffer();// 清空resp
ServletOutputStream sos = resp.getOutputStream();
ImageIO.write(buffer, "jpg", sos);//二维图片打印成指定格式
sos.flush();
sos.close();
}
// 生成验证码
private String generateCheckcode(int len) {
char[] res = new char[len];
Random r = new Random();
for (int i = 0; i < len; i++)
res[i] = source.charAt(r.nextInt(source.length()));
return new String(res);
}
复制代码
} 2.调用Controller层 @RequestMapping(value = "login", method = RequestMethod.POST) public String login(@Validated(UserGroup.LoginGroup.class) @ModelAttribute("user") UserBean user, HttpSession session,Errors errors, Model model) throws Exception { Object obj = session.getAttribute("checkcode"); String code = user.getCheckcode(); if(code != null && !code.equals(obj)) errors.rejectValue("checkcode", null, null, "验证码输入错误"); if (errors.hasErrors()) { model.addAttribute("msg", "登录失败!请重新登录"); return "user/login"; } boolean bb = userService.login(user); if (bb) { return "user/info"; } else { model.addAttribute("msg", "登录失败!请重新登录"); return "user/login"; }
3.Jsp页面层
<form:form action="{msg} <form:label path="username">账号:</form:label> <form:input path="username"/> <form:errors path="username" cssClass="error" /> <form:label path="password">密码:</form:label> <form:password path="password" /> <form:errors path="password" cssClass="error" /> <form:label path="checkcode">校验码:</form:label> <form:input path="checkcode" /> <form:errors path="checkcode" cssClass="error" /> 点击刷新 </form:form>