Spring MVC 中使用 Google kaptcha 验证码

   验证码是抵抗批量操作和恶意登录最有效的方式之一。

   验证码从产生到现在已经衍生出了很多分支、方式。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);

 

posted @ 2017-09-26 16:47  Orson  阅读(990)  评论(0编辑  收藏  举报