制作验证码用到的类:
1.BufferedImage图像数据缓冲区
2.Graphics绘制图片
3.Color获取颜色
4.Random生成随机数
5.ImageIO输出图片
生成图片的实现类
ImageServlet类
1.定义BufferedImage对象
2.获得Graphics对象
3.通过Random产生随机验证码信息
4.使用Graphics绘制图片
5.记录验证码信息到session中
6.使用ImageIO输出图片
校验验证码是否正确
LoginServlet类
1.获取页面验证码
2.获取session保存的验证码
3.比较验证码
4.返回校验结果
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title heretitle>
<script type="text/javascript">
function reloadCode(){
var time=new Date().getTime();
document.getElementById("checkcode").src="<%=request.getContextPath()%>/servlet/imageServlet?d="+time;
}
script>
head>
<body>
这是我写的第一个验证码界面!
<hr>
验证码:<input type="text" name="checkcode" />
<img alt="验证码" id="checkcode" src="<%=request.getContextPath()%>/servlet/imageServlet" />
<a href="javascript:reloadCode();">刷新a>
body>
html>
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//定义BufferedImage对象图像缓冲,参数 宽 高 类型
BufferedImage bi=new BufferedImage(68,22,BufferedImage.TYPE_INT_RGB);
//获得Graphics对象,绘制图片
Graphics g=bi.getGraphics();
//获取颜色
Color c=new Color(200,150,255);
g.setColor(c);
//颜色有了,此时需要画一个背景框
g.fillRect(0, 0, 68, 22);
//接下来我们画验证码图片里的内容,字母和数字的组合
char[] ch= "ABCDEFGHRJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
Random r=new Random();
int len=ch.length;
int index;
StringBuffer sb=new StringBuffer();
for(int i=0;i<4;i++) {
index=r.nextInt(len);
//更换随机颜色
g.setColor(new Color(r.nextInt(88),r.nextInt(188),r.nextInt(255)));
//把字符画上去
g.drawString(ch[index]+"", (i*15)+3, 18);
//把字符保存到一个字符串
sb.append(ch[index]);
}
request.getSession().setAttribute("checkcode", sb);
//使用ImageIO输出图片
ImageIO.write(bi, "JPG", response.getOutputStream());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String checkcodeString=(request.getSession().getAttribute("checkcode")).toString();
String checkcodeStringYongHu=request.getParameter("checkcode");
checkcodeStringYongHu=checkcodeStringYongHu.toUpperCase();//变为大写
System.out.println(checkcodeString);
System.out.println(checkcodeStringYongHu);
response.setCharacterEncoding("utf-8");//必须在后者前面
PrintWriter pw=response.getWriter();
if(checkcodeStringYongHu.equals(checkcodeString)) {
pw.println("验证码核验成功");
}else {
pw.println("验证码核验失败");
}
}
这里遇到两个问题,一个是空指针异常,一个是响应的输出转换不过来一直是乱码
第一个是由于参数设置有问题读取到的用户请求里的验证码,读不到。第二个乱码问题,一般使用response.setContentType()方法来设置HTTP 响应的编码,同时指定了浏览器显示的编码;
因为他在执行该方法通知服务器端以指定编码进行编码后,会自动调用response.setCharacterEncoding()方法来通知浏览器以指定编码来解码;使用此方法要在response.getWriter()执行之前或response提交之前。
开源组件实现验证码
1.Jcaptcha:一个用来生成图形验证码的Java开源组件,使用起来也是非常的简单方便。与Spring组合使用,可产生多种形式的验证码。
2.Kaptcha:一个非常实用的验证码生成工具,有了它,可以生成各种样式的验证码,因为它是可配置的
下载kaptcha-2.3.jar
将jar包导入项目
编写页面
配置web.xml
启动项目
使用Kaptcha开源组件
web.xml配置
<servlet>
<servlet-name>Kaptchaservlet-name>
<servlet-class>com.google.code.Kaptcha.servlet.KaptchaServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>Kaptchaservlet-name>
<url-pattern>/randomcode.jpgurl-pattern>
servlet-mapping>
还有其他配置
web.xml的配置
<servlet>
<servlet-name>Kaptchaservlet-name>
<servlet-class>
KaptchaServlet
servlet-class>
<init-param>
<description>图片边框,合法值:yes , nodescription>
<param-name>kaptcha.borderparam-name>
<param-value>yesparam-value>
init-param>
<init-param>
<description>
边框颜色,合法值: r,g,b (and optional alpha) 或者
white,black,blue.
description>
<param-name>kaptcha.border.colorparam-name>
<param-value>blackparam-value>
init-param>
<init-param>
<description>边框厚度,合法值:>0description>
<param-name>kaptcha.border.thicknessparam-name>
<param-value>1param-value>
init-param>
<init-param>
<description>图片宽 200description>
<param-name>kaptcha.image.widthparam-name>
<param-value>200param-value>
init-param>
<init-param>
<description>图片高 50description>
<param-name>kaptcha.image.heightparam-name>
<param-value>50param-value>
init-param>
<init-param>
<description>图片实现类description>
<param-name>kaptcha.producer.implparam-name>
<param-value>
com.google.code.kaptcha.impl.DefaultKaptcha
param-value>
init-param>
<init-param>
<description>文本实现类description>
<param-name>kaptcha.textproducer.implparam-name>
<param-value>
com.google.code.kaptcha.text.impl.DefaultTextCreator
param-value>
init-param>
<init-param>
<description>文本集合,验证码值从此集合中获取description>
<param-name>kaptcha.textproducer.char.stringparam-name>
<param-value>1234567890param-value>
init-param>
<init-param>
<description>验证码长度 5description>
<param-name>kaptcha.textproducer.char.lengthparam-name>
<param-value>2param-value>
init-param>
<init-param>
<description>字体 Arial, Courierdescription>
<param-name>kaptcha.textproducer.font.namesparam-name>
<param-value>Arial, Courierparam-value>
init-param>
<init-param>
<description>字体大小 40px.description>
<param-name>kaptcha.textproducer.font.sizeparam-name>
<param-value>40param-value>
init-param>
<init-param>
<description>
字体颜色,合法值: r,g,b 或者 white,black,blue.
description>
<param-name>kaptcha.textproducer.font.colorparam-name>
<param-value>blackparam-value>
init-param>
<init-param>
<description>文字间隔 2description>
<param-name>kaptcha.textproducer.char.spaceparam-name>
<param-value>2param-value>
init-param>
<init-param>
<description>干扰实现类description>
<param-name>kaptcha.noise.implparam-name>
<param-value>
com.google.code.kaptcha.impl.DefaultNoise
param-value>
init-param>
<init-param>
<description>
干扰颜色,合法值: r,g,b 或者 white,black,blue.
description>
<param-name>kaptcha.noise.colorparam-name>
<param-value>blackparam-value>
init-param>
<init-param>
<description>
图片样式: 水纹com.google.code.kaptcha.impl.WaterRipple
鱼眼com.google.code.kaptcha.impl.FishEyeGimpy
阴影com.google.code.kaptcha.impl.ShadowGimpy
description>
<param-name>kaptcha.obscurificator.implparam-name>
<param-value>
com.google.code.kaptcha.impl.WaterRipple
param-value>
init-param>
<init-param>
<description>背景实现类description>
<param-name>kaptcha.background.implparam-name>
<param-value>
com.google.code.kaptcha.impl.DefaultBackground
param-value>
init-param>
<init-param>
<description>背景颜色渐变,开始颜色description>
<param-name>kaptcha.background.clear.fromparam-name>
<param-value>greenparam-value>
init-param>
<init-param>
<description>背景颜色渐变,结束颜色description>
<param-name>kaptcha.background.clear.toparam-name>
<param-value>whiteparam-value>
init-param>
<init-param>
<description>文字渲染器description>
<param-name>kaptcha.word.implparam-name>
<param-value>
com.google.code.kaptcha.text.impl.DefaultWordRenderer
param-value>
init-param>
<init-param>
<description>
session中存放验证码的key键
description>
<param-name>kaptcha.session.keyparam-name>
<param-value>KAPTCHA_SESSION_KEYparam-value>
init-param>
<init-param>
<description>
The date the kaptcha is generated is put into the
HttpSession. This is the key value for that item in the
session.
description>
<param-name>kaptcha.session.dateparam-name>
<param-value>KAPTCHA_SESSION_DATEparam-value>
init-param>
servlet>
<servlet-mapping>
<servlet-name>Kaptchaservlet-name>
<url-pattern>/randomcode.jpgurl-pattern>
servlet-mapping>