首先引入 easy-captcha-1.6.2-RELEASE.jar
1、生成字母验证码
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
SpecCaptcha captcha = new SpecCaptcha(120, 40, 4);
request.getSession().setAttribute("pic", captcha.text());
captcha.out(response.getOutputStream());
}
2、生成计算式验证码
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ArithmeticCaptcha captcha = new ArithmeticCaptcha(200, 40, 4);
request.getSession().setAttribute("pic", captcha.text());
captcha.out(response.getOutputStream());
}
3、生成GIF验证码
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
GifCaptcha captcha=new GifCaptcha(120, 40, 4);
request.getSession().setAttribute("pic", captcha.text());
captcha.out(response.getOutputStream());
}
4、生成汉字验证码
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
ChineseCaptcha captcha=new ChineseCaptcha(120, 40, 4);
request.getSession().setAttribute("pic", captcha.text());
captcha.out(response.getOutputStream());
}
5、生成汉字GIF验证码
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
ChineseGifCaptcha captcha=new ChineseGifCaptcha(120, 40, 4);
request.getSession().setAttribute("pic", captcha.text());
captcha.out(response.getOutputStream());
}
前端:验证码看不清,点击换一张
<form method="post" action="/get.do">
<p>验证码:<input type="text" name="captcha">
<img src="/ch" onclick="this.src='/ch?t='+Math.random()"/>
</p>
<input type="submit" value="提交">
</form>