验证码生成库Kaptcha

来源:互联网 发布:电脑截图软件排名 编辑:程序博客网 时间:2024/06/06 13:24

Kaptcha 是一个生成验证码的库,是google code中的一个项目。

下载地址:http://code.google.com/p/kaptcha/

使用Kaptcha可以生成验证码文本和验证码图片,将验证码文本放入HttpSession中以供校验,生成的验证码图片返回给客户端。

使用kaptcha可以方便的配置:

 

  • 验证码的字体
  • 验证码字体的大小
  • 验证码字体的字体颜色
  • 验证码内容的范围(数字,字母,中文汉字!)
  • 验证码图片的大小,边框,边框粗细,边框颜色
  • 验证码的干扰线(可以自己继承com.google.code.kaptcha.NoiseProducer写一个自定义的干扰线)
  • 验证码的样式(鱼眼样式、3D、普通模糊……当然也可以继承com.google.code.kaptcha.GimpyEngine自定义样式
 
下面是在springmvc中使用kaptcha的一个例子:
applicationContext.xml:
<bean id="productor" class="com.google.code.kaptcha.impl.DefaultKaptcha">
  <property name="config">
   <bean class="com.google.code.kaptcha.util.Config">
    <constructor-arg name="properties" type="java.util.Properties">
     <props>
      <prop key="kaptcha.border">no</prop>
      <prop key="kaptcha.textproducer.font.color">black</prop>
      <prop key="kaptcha.textproducer.char.space">5</prop>
      <prop key="kaptcha.textproducer.font.names">宋体,楷体,微软雅黑</prop>
     </props>
    </constructor-arg>
   </bean>
  </property>
 </bean>
 
Controller:

@Controller
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private Producer producer;

    @RequestMapping("/register.do")
    public String register(HttpServletRequest req, HttpSession session, String name, String password,
            String varificationCode) {
        boolean fail = false;
        if (varificationCode == null) {
            fail = true;
        } else if (!varificationCode.equals(session.getAttribute("varificationConde"))) {
            fail = true;
        }
        if (fail) {
            session.removeAttribute("varificationConde");
            return "error";
        }

        User user = new User();
        user.setName(name);
        user.setPassword(password);
        this.userService.save(user);
        return "success";
    }

    @RequestMapping("/generateVerificationCode.do")
    public void generateVerificationCode(HttpServletResponse resp, HttpSession session, ServletOutputStream out)
            throws IOException {
        ImageIO.setUseCache(false);
        String varificationConde = this.producer.createText();
        session.setAttribute("varificationConde", varificationConde);
        BufferedImage bi = this.producer.createImage(varificationConde);
        // Set to expire far in the past.
        resp.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        resp.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        resp.setHeader("Pragma", "no-cache");
        // return a jpeg
        resp.setContentType("image/jpeg");
        // write the data out
        ImageIO.write(bi, "jpg", out);
    }

}

原创粉丝点击