我们自己编写验证码过于麻烦,所以一般会编写验证码插件或直接使用其他人的插件,这里推荐一个EasyCaptcha验证码插件,简单易用。
1.添加maven依赖
<!-- https://mvnrepository.com/artifact/com.github.whvcse/easy-captcha -->
<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()是传入的时间戳,让验证码的内容随之改变。页面效果如下。
最后在登录的时候对验证码进行校验就可以了
版权声明:本文为weixin_53402685原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。