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 @   Orson  阅读(1015)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示