验证码插件EasyCaptcha

1.添加maven依赖

<dependency>
      <groupId>com.github.whvcse</groupId>
      <artifactId>easy-captcha</artifactId>
      <version>1.6.2</version>
    </dependency>

2.使用工具类

在servlet中创建一个方法只需要两步就可以在页面中使用验证码

 @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        GifCaptcha c = new GifCaptcha();
        CaptchaUtil.out(c,req,resp);
        //req.getSession().setAttribute("captcha","sfsx");
    }

CaptchaUtil是EasyCaptcha中引入的工具类,它内部有很多属性和out方法,其中一个是

 public static void out(Captcha captcha, HttpServletRequest request, HttpServletResponse response) throws IOException {
        setHeader(response);
        request.getSession().setAttribute("captcha", captcha.text().toLowerCase());
        captcha.out(response.getOutputStream());
    }

这个方法会把验证码的内容存到session中的captcha上,我们只需要调用就可以得到验证码的值

3.在页面中使用验证码

<form action="check" method="post">
    <label>账号:<input type="text" name="account"></label><br>
    <label>密码:<input type="password" name="pwd"></label><br>
    <label>验证码:<input type="text" name="code"></label>
    <label><img src="check" onclick="this.src='check?'+ new Date()" alt=""></label>
    <br>
    <input type="submit" value="登录">
</form>

check是定义的servlet的名称,返回后就是验证码,添加onclick事件单击改变验证码的内容,new Date()是传入的时间戳,让验证码的内容随之改变。页面效果如下。

最后在登录的时候对验证码进行校验就可以了

本文作者:岁月记忆

本文链接:https://www.cnblogs.com/huang2979127746/p/16948389.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   岁月记忆  阅读(319)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起