设置项目编码 utf-8
<%@ page language=”java” contentType=”text/html; charset=UTF-8” pageEncoding=”UTF-8”%>
在控制层类上加入
@SessionAttributes(value={"randImage"})
/***
* 获取验证码
* @param model
* @param response
*/
@RequestMapping(value="/getRandCode",method = RequestMethod.GET)
public void getRandCode(ModelMap model,HttpServletResponse response){
try {
model.addAttribute("randImage",userService.writeImg(response.getOutputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
login.jsp 页面
<span><img id="randImage" src="${contextPath}/login/getRandCode?id=<%=System.currentTimeMillis()%>" alt="看不清,换一个" /></span>
service层方法
/*
* 产生验证码
*/
public String writeImg(OutputStream stream) {
// 设置图形大小。
int width = 86, height = 24;
// 建立图形缓冲区。
BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();// 获得 Graphics 对象。
g.setColor(getRandomColor(180, 240));// 设置背景色。
g.fillRect(0, 0, width, height);// 填充背景。
StringBuilder validationCode = new StringBuilder();// 用于保存最后的验证码
String[] fontNames = {"微软雅黑"};// 用于随机的字体的集合
Random r = new Random();
// 随机生成4个验证码
for (int i = 0; i < 4; i++) {
g.setFont(new Font(fontNames[0], Font.PLAIN, height-4));
char codeChar = codeChars.charAt(r.nextInt(codeChars.length()));
validationCode.append(codeChar);
g.setColor(getRandomColor(40, 60));
g.drawString(String.valueOf(codeChar), 20 * i + r.nextInt(5),height - 4);// 在图形上输出验证码
}
// 随机生干扰码
for (int i = 0; i < 30; i++) {
g.setColor(getRandomColor(100, 200));
int x = r.nextInt(width);
int y = r.nextInt(height);
g.drawLine(x, y, x + r.nextInt(10), y + r.nextInt(5));
}
g.dispose();// 关闭Graphics对象
OutputStream os = stream;// 得到输出流
try {
ImageIO.write(image, "JPEG", os);
} catch (IOException e) {
e.printStackTrace();
}// 以JPEG格式向客户端发送图形验证码
return validationCode.toString();
}
/**
* 产生随机的颜色
*
* @param minColor
* @param maxColor
* @return
*/
private static Color getRandomColor(int minColor, int maxColor) {
Random r = new Random();
int red = minColor + r.nextInt(maxColor - minColor);
int green = minColor + r.nextInt(maxColor - minColor);
int blue = minColor + r.nextInt(maxColor - minColor);
return new Color(red, green, blue);
}
Logincontroller
/***
* 检查图片验证码是否相等
* @param randImage
* @param inputRandCode
* @return
*/
@RequestMapping(value="/checkRandCode",method = RequestMethod.GET)
@ResponseBody
public boolean checkRandCode(@ModelAttribute("randImage") String randImage,String inputRandCode){
if(randImage.equalsIgnoreCase(inputRandCode)){
return true;
}
return false;
}
loginController 在登陆时候的校验
//验证码
if(!checkRandCode(randImage,randCode)){
model.addAttribute("authCodeError", "验证码不正确!");
return "admin/login";
}
login.js中
var $randImage = $("img[id=randImage]");//验证码图片
$randImage.click(function(){
$randCode.val("");
$randImage.attr("src",getRootPath()+"/login/getRandCode?id="+Math.random());
});