使用谷歌插件生成验证码

本文是在ssm框架中使用谷歌插件生成验证码以及控制层验证

首先导入依赖

<!-- 集成验证码 -->
<dependency>
    <groupId>com.github.axet</groupId>
    <artifactId>kaptcha</artifactId>
    <version>0.0.9</version>
</dependency>
在springmvc配置文件中配置如下
<!-- Kaptcha验证码生成器 -->
<bean name="producer" class="com.google.code.kaptcha.impl.DefaultKaptcha" scope="singleton">
   <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.color">black</prop><!--生成验证码的长度为4-->

            </props>
         </constructor-arg>
      </bean>
   </property>
</bean>

控制层

@Autowired
private Producer producer;//这里是谷歌的包   不要导错包

@RequestMapping("/captcha.jpg")
public void captcha(HttpServletResponse response, HttpSession session)throws ServletException, IOException {
    response.setHeader("Cache-Control", "no-store, no-cache");
    response.setContentType("image/jpeg");
    //生成文字验证码
    String text = producer.createText();
    //生成图片验证码
    BufferedImage image = producer.createImage(text);
    //保存到shiro session
    session.setAttribute(Constant.KAPTCHAR_KEY, text);
    ServletOutputStream out = response.getOutputStream();
    ImageIO.write(image, "jpg", out);
    out.flush();
} 

假如登录时使用验证码:

    @RequestMapping("/login")
    @ResponseBody
    public R toLogin(String username, String password, String yzm, HttpServletRequest request){
        String text = (String) request.getSession().getAttribute(Constant.KAPTCHAR_KEY);//从缓存中取出验证码信息
        System.out.println(text+"--"+yzm+"--"+text.equalsIgnoreCase(yzm));
        if (!text.equalsIgnoreCase(yzm)){
            return R.error("验证码输入错误");//返回错误信息   R是一个异常类  工具需要自行更改
        }
        return  loginInfoService.login(username,password,request);//这是登录查询,这里就不在赘述
    }

这里是验证码使用到的工具类   为了保证验证码存到缓存和取出来是同一个 

public class Constant {
    public  static final String KAPTCHAR_KEY = "KAPTCHAR_KEY";
    public static final String VERIFY_CODE="VERIFY_CODE";
}

猜你喜欢

转载自blog.csdn.net/leyili_s/article/details/79721516