网页图形验证码的实现
验证码
验证码(CAPTCHA)是“Completely Automated Public Turing test to tell Computers and Humans Apart”(全自动区分计算机和人类的图灵测试)的缩写
是一种区分用户是计算机还是人的公共全自动程序。
图形验证码原理
服务器端随机生成图片验证码,发送到客户端。
自己编写的生成验证码类
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
public class VerifiCode {
private int weight=100 ;
private int height=50 ;
private String text;
private Random r=new Random();
private String[] fontNames={"宋体" ,"华文楷体" , "黑体" , "微软雅黑" , "楷体_GB2312" };
private String codes="23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ" ;
private Color randomColor () //获取随机的颜色
{
int r=this .r.nextInt(150 );
int g=this .r.nextInt(150 );
int b=this .r.nextInt(150 );
return new Color(r,g,b);
}
private Font randomFont () //获取随机字体
{
int index=r.nextInt(fontNames.length);
String fontName=fontNames[index];
int style=r.nextInt(4 );
int size=r.nextInt(5 )+24 ;
return new Font(fontName,style,size);
}
private char randomChar () //获取随机字符
{
int index=r.nextInt(codes.length());
return codes.charAt(index);
}
private void drawLine (BufferedImage image) //画干扰线,验证码干扰线用来防止计算机解析图片
{
int num=3 ;
Graphics2D g=(Graphics2D) image.getGraphics();
for (int i=0 ;i<num;i++)
{
int x1=r.nextInt(weight);
int y1=r.nextInt(height);
int x2=r.nextInt(weight);
int y2=r.nextInt(height);
g.setColor(randomColor());
g.drawLine(x1, y1, x2, y2);
}
}
private BufferedImage createImage () //创建图片的方法
{
BufferedImage image=new BufferedImage(weight,height,BufferedImage.TYPE_INT_RGB);
Graphics2D g=(Graphics2D) image.getGraphics();
g.setColor(Color.GRAY);
g.fillRect(0 , 0 , weight, height);
return image;
}
public BufferedImage getImage () //获取验证码图片的方法
{
BufferedImage image=createImage();
Graphics2D g=(Graphics2D) image.getGraphics();
StringBuilder sb=new StringBuilder();
for (int i=0 ;i<4 ;i++)
{
String s=randomChar()+"" ;
sb.append(s);
float x=i*1.0 F*weight/4 ;
g.setFont(randomFont());
g.setColor(randomColor());
g.drawString(s, x, height-5 );
}
this .text=sb.toString();
drawLine(image);
return image;
}
public String getText () //获取验证码文本的方法
{
return text;
}
public static void output (BufferedImage image,OutputStream out) throws IOException //将验证码图片写出的方法
{
ImageIO.write(image, "JPEG" , out);
}
}
登陆页面加入验证码
登陆页面 Login.jsp
<html >
<head >
<meta http-equiv ="Content-Type" content ="text/html; charset=utf-8" >
<title > Insert title here</title >
<script type ="text/javascript" >
function change ()
{
var img=document.getElementById("image" );
img.src="/SessionTest/VerificodeServlet?a=" new Date ().getTime();
}
</script >
</head >
<body >
<h1 > 登陆页面</h1 >
<form action ="/SessionTest/LoginServlet" method ="post" >
用户名:<input type ="text" name ="username" > <br />
密 码:<input type ="password" name ="password" > <br />
验证码:<input type ="text" name ="vcode" size ="3" >
<img src ="/SessionTest/VerificodeServlet" id ="image" > //请求Servlet获取验证码
<a href ="javascript:change()" > 看不清,换一张</a > //点击即刷新
<br />
<input type ="submit" value ="登陆" >
</form >
<%
String message="" ;
String msg=(String )request .getAttribute("msg" );
if (msg!=null )
{
message=msg;
}
%>
<font color ="red" >
<%=message %>
</font >
</body >
</html >
生成验证码的servlet
public class VerificodeServlet extends HttpServlet {
protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
VerifiCode v=new VerifiCode();
BufferedImage image=v.getImage();
request.getSession().setAttribute("text" , v.getText());
v.output(image, response.getOutputStream());
}
}
判断登陆页面的Servlet
public class LoginServlet extends HttpServlet {
protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8" );
String session_vcode=(String) request.getSession().getAttribute("text" );
String form_vcode=request.getParameter("vcode" );
if (!(session_vcode.equalsIgnoreCase(form_vcode)))
{
request.setAttribute("msg" , "验证码错误" );
request.getRequestDispatcher("/session2/Login.jsp" ).forward(request, response);
return ;
}
String name=request.getParameter("username" );
String passwd=request.getParameter("password" );
if ((name.equals("cuiandong" ))&&(passwd.equals("123456" )))
{
HttpSession hs=request.getSession();
hs.setAttribute("user" , name);
response.sendRedirect("/SessionTest/session2/success.jsp" );
}
else
{
request.setAttribute("msg" , "用户名或密码错误" );
request.getRequestDispatcher("/session2/Login.jsp" ).forward(request, response);
}
}
}