kaptcha生成验证码

Meven的pom.xml中加入

<!--验证码-->
<dependency>
     <groupId>com.github.axet</groupId>
     <artifactId>kaptcha</artifactId>
     <version>0.0.9</version>
</dependency>

Spring中声明

<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.image.width">125</prop>
                    <prop key="kaptcha.image.height">60</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>

编写Controller

@Controller
@RequestMapping("/account")
public class AccountController extends AdminBaseController {

    Producer captchaProducer = null;

    @Autowired
    public void setCaptchaProducer(Producer captchaProducer) {
        this.captchaProducer = captchaProducer;
    }

    @RequestMapping("/kaptchaGet")
    public ModelAndView doGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setDateHeader("Expires", 0);
        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");
        // return a jpeg
        response.setContentType("image/jpeg");
        // create the text for the image
        String capText = captchaProducer.createText();
        // store the text in the session
        request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
        // create the image with the text
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        // write the data out
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        System.out.println("Captchca:"+request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY));
        return null;
    }

    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public AjaxResult login(LoginModel model,HttpServletRequest request) {
        String captcha = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);

        /*if (!model.getCaptcha().equals(captcha))
            return ajaxResult(false, "验证码不正确");*/

        ......

        return ajaxResult(true,"");
    }

}

login界面

<div class="form-group">
        <label class="control-label visible-ie8 visible-ie9">验证码</label>
        <input class="form-control placeholder-no-fix validate[required]" type="text" autocomplete="off"
               placeholder="验证码" name="captcha"/>
        <div class="input-icon">
            <img id="captcha1" alt="如果看不清楚,请单击图片刷新!" src="/account/kaptchaGet">
            &nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:;" onclick="refreshCaptcha()">点击刷新</a>
        </div>
</div>

Js

function refreshCaptcha(){
    var ran = Math.floor(Math.random() * 100)
    $('#captcha1').attr('src','/account/kaptchaGet?' + ran);
}

完成效果

http://imglf5.nosdn.127.net/img/TTMwdVJSKzM0MmhRbDYzakVrTlNiZThlV3l2UzJEcGx1ZjJzV2FTUnI5ekczeC9hRG9xMldnPT0.png?imageView&thumbnail=500x0&quality=96&stripmeta=0

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您提供制作验证码的步骤: 1. 添加依赖 在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>com.github.axet</groupId> <artifactId>kaptcha</artifactId> <version>0.0.9</version> </dependency> ``` 2. 配置 Kaptcha 在 application.properties 或 application.yml 文件中添加以下配置: ```yaml kaptcha: border: no border.color: black textproducer.font.color: black textproducer.char.length: 4 noise.impl: com.github.axet.kaptcha.impl.DefaultNoise noise.color: black ``` 这些配置项可以根据实际需求进行修改。 3. 生成验证码 在控制器中添加以下代码: ```java @GetMapping("/captcha.jpg") public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception { // 创建 Kaptcha 对象 ConfigurableKaptcha kaptcha = new ConfigurableKaptcha(); // 生成验证码 String code = kaptcha.createText(); // 将验证码存入 Session request.getSession().setAttribute("captcha", code); // 将验证码输出到页面 response.setContentType("image/jpeg"); ServletOutputStream outputStream = response.getOutputStream(); BufferedImage image = kaptcha.createImage(code); ImageIO.write(image, "jpg", outputStream); outputStream.flush(); outputStream.close(); } ``` 这段代码会在 /captcha.jpg 路径下生成验证码图片,并将验证码存入 Session 中。 4. 验证验证码 在需要验证验证码的地方,可以使用如下代码: ```java String captcha = request.getParameter("captcha"); String sessionCaptcha = (String) request.getSession().getAttribute("captcha"); if (!captcha.equalsIgnoreCase(sessionCaptcha)) { // 验证码错误 } ``` 这段代码会从请求参数中获取验证码,然后和 Session 中的验证码进行比对,如果不一致则说明验证码错误。 以上就是使用 Kaptcha 制作验证码的步骤,希望对您有帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值