给Java项目增加验证码支持

转载自 http://www.icoolxue.com/blog/show/3


在做网站或者其它项目(如QQ登录时有可能会让你输入验证码)时,为了防止应用被恶意用户攻击,可以考虑增加验证码支持。要增加验证码支持,在Java的世界中,大概有四种方式:

  1. 自己实现(使用Java2D)。
  2. 使用Kaptcha。
  3. 使用Jcaptcha。
  4. 使用Google的验证码API(Google的验证码服务很好很安全,但是大陆不能用)。

自己实现验证码不太现实,当然如果你有时间的话也可以!所以在Kaptcha和Jcaptcha里选择,个人使用上来看,Jcaptcha比Kaptcha复杂得多,不考虑。

Kaptcha的包自带了Servlet,如果你是简单的Java Web项目,配置好这些Servlet就可以了,如果你要在SpringMVC项目中使用Kaptcha,可以像下面这样操作:

  • 增加Kaptcha的库文件。
<!-- Kaptcha验证码框架 -->
<dependency>
    <groupId>com.github.axet</groupId>
    <artifactId>kaptcha</artifactId>
    <version>0.0.9</version>
    <scope>${scope.release}</scope>
</dependency>

如果你是非Maven项目,请下载Kaptcha的JAR包放到项目Classpath下就行。

  • 配置Kaptcha:
<!-- Kaptcha验证码生成器 -->
<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">yes</prop>
                    <prop key="kaptcha.border.color">105,179,90</prop>
                    <prop key="kaptcha.textproducer.font.color">blue</prop>
                    <prop key="kaptcha.obscurificator.impl">com.google.code.kaptcha.impl.ShadowGimpy</prop>
                    <prop key="kaptcha.image.width">125</prop>
                    <prop key="kaptcha.image.height">45</prop>
                    <prop key="kaptcha.textproducer.font.size">45</prop>
                    <prop key="kaptcha.session.key">code</prop>
                    <prop key="kaptcha.textproducer.char.length">4</prop>
                    <prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop>
                </props>
            </constructor-arg>
        </bean>
    </property>
</bean>

更多的属性设置可以在com.google.code.kaptcha.Constants类中找到。其中包括:

kaptcha.border.color:边框颜色

kaptcha.border.thickness:边框宽度

kaptcha.textproducer.char.length:产生字符的长度

kaptcha.textproducer.font.size:产生字符的大小

kaptcha.image.width:产生图片的宽度

kaptcha.image.height:产生图片的高度,等

  • 配置Kaptcha的Controller:
@Controller
@RequestMapping("/captcha")
public class CaptchaController {

    @Autowired
    private Producer producer;

    @RequestMapping(value = "", method = RequestMethod.GET)
    public void kaptcha(HttpServletRequest req,
            HttpServletResponse rsp) throws Exception {
        HttpSession session = req.getSession();
        String code = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        System.out.println("验证码: " + code);

        rsp.setDateHeader("Expires", 0);
        rsp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        rsp.addHeader("Cache-Control", "post-check=0, pre-check=0");
        rsp.setHeader("Pragma", "no-cache");
        rsp.setContentType("image/jpeg");

        String capText = producer.createText();
        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);

        BufferedImage image = producer.createImage(capText);
        ServletOutputStream out = rsp.getOutputStream();
        ImageIO.write(image, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }
}

代码可以直接Copy到你的项目中使用。

  • 在需要验证码的Controller里验证Kaptcha:
/**
 * 验证码工具类
 *
 * @author Storezhang
 */
public class CaptchaUtils {

    public static boolean verify(HttpServletRequest request) {
        //从session中取出servlet生成的验证码text值
        String expected = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        //获取用户页面输入的验证码
        String received = request.getParameter("kaptcha");
        return received != null && received.equalsIgnoreCase(expected);
    }
}

经过以上配置,你就可以正常使用Kaptcha了,当然别忘了Kaptcha只是一张图片,你需要在前台输出这张图片:

<form action="kaptcha" method="post">
    <input type="text" name="kaptchaValidate">
    <img id="vcode" style="vertical-align: middle;" title="点击更换" alt="验证图片" src="kaptcha.jpg" height="40" width="85">
    <input type="submit" value="提交">
</form>

使用Kaptcha生成的验证码效果图:


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值