1. 程式人生 > >Spring MVC 中使用 Google kaptcha 驗證碼

Spring MVC 中使用 Google kaptcha 驗證碼

實用 pri 集成 auto req post bsp produce target

驗證碼是抵抗批量操作和惡意登錄最有效的方式之一。

驗證碼從產生到現在已經衍生出了很多分支、方式。google kaptcha 是一個非常實用的驗證碼生成類庫。

通過靈活的配置生成各種樣式的驗證碼,並將生成的驗證碼字符串放到 HttpSession 中,方便獲取進行比較。

本文描述在 spring mvc 下快速的將 google kaptcha 集成到項目中(單獨使用的話在 web.xml 中配置 KaptchaServlet)。

1.maven 依賴

官方提供的 pom 無法正常使用,使用阿裏雲倉庫對應 kaptcha。

<!-- google 驗證碼 
--> <dependency> <groupId>com.github.penggle</groupId> <artifactId>kaptcha</artifactId> <version>${kaptcha.version}</version> </dependency>

2.前端

<img id="kaptchaImage" src="${pageContext.request.contextPath}/captcha-image" width
="116" height="36">
    $(function(){
        $(‘#kaptchaImage‘).click(function () {
            $(this).hide().attr(‘src‘, ‘${ctx}/captcha-image?‘ + Math.floor(Math.random()*100) ).fadeIn();
            event.cancelBubble=true;
        });
    });

3.mvc-context 配置

 <!--goole captcha 驗證碼配置
--> <bean id="captchaProducer" class="com.google.code.kaptcha.impl.DefaultKaptcha"> <property name="config"> <bean class="com.google.code.kaptcha.util.Config"> <constructor-arg> <props> <prop key="kaptcha.border">no</prop> <prop key="kaptcha.textproducer.font.size">45</prop> <prop key="kaptcha.textproducer.font.color">blue</prop> <prop key="kaptcha.textproducer.char.length">4</prop> <prop key="kaptcha.session.key">code</prop> </props> </constructor-arg> </bean> </property> </bean>

更多參數:http://www.cnblogs.com/louis80/p/5230507.html

4.服務端

@Controller
public class CaptchaController {

    private final Producer captchaProducer;

    @Autowired
    public CaptchaController(Producer captchaProducer) {
        this.captchaProducer = captchaProducer;
    }

    @RequestMapping(value = "captcha-image")
    public String getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        String capText = captchaProducer.createText();
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);

        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }
}

5.session 中獲取驗證碼

request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);

Spring MVC 中使用 Google kaptcha 驗證碼