利用谷歌 kaptcha 进行验证码生成

 package main.com.smart.controller;

 import com.google.code.kaptcha.Producer;
import main.com.smart.utils.CaptchaProducer;
import main.com.smart.utils.RedisClient;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView; import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import com.google.code.kaptcha.Constants; import java.awt.image.BufferedImage; /**
* 验证码 生成控制器
*
* @author yang ming
* @create 2016-04-29 12:17
*/ @Controller
@RequestMapping("/kaptcha")
public class CaptchaController {
/**
* 使用方法
* get: http://localhost:8080/smart/kaptcha
*/
private static final Logger log = Logger.getLogger(CaptchaController.class);
@Autowired
private Producer captchaProducer = null; @RequestMapping
public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
RedisClient client = RedisClient.getInstance();
//在控制器中获取验证码
//String kaptchaExpected = (String) request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
log.info("获取验证"); log.info(Constants.KAPTCHA_SESSION_KEY);
HttpSession session = request.getSession();
String code1 = client.getValue(Constants.KAPTCHA_SESSION_KEY);
String code = String.valueOf(session.getAttribute(Constants.KAPTCHA_SESSION_KEY));
//System.out.println("******************验证码是: " + code + "******************"); response.setDateHeader("Expires", 0); // Set standard HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
response.addHeader("Cache-Control", "post-check=0, pre-check=0"); // Set standard HTTP/1.0 no-cache header.
response.setHeader("Pragma", "no-cache"); // return a jpeg
response.setContentType("image/jpeg"); // create the text for the image
String[] array = CaptchaProducer.getCaptchaText();
//String capText = captchaProducer.createText();
//int param1 = (int)capText.charAt(0);
//int param2 = (int)capText.charAt(1);
Integer result = Integer.valueOf(array[0]) + Integer.valueOf(array[1]); // store the text in the session
client.setValue(Constants.KAPTCHA_SESSION_KEY, result.toString());
//session.setAttribute(Constants.KAPTCHA_SESSION_KEY, result); // create the image with the text
BufferedImage bi = captchaProducer.createImage(array[0]+"+"+array[1]+"=?");
ServletOutputStream out = response.getOutputStream(); // write the data out
ImageIO.write(bi, "jpg", out);
try {
out.flush();
} finally {
out.close();
}
return null;
} }
上一篇:多版本号并发控制(MVCC)在分布式系统中的应用


下一篇:YII中表单验证