动手实现随机验证码
首先,来写一个画验证码图片的Java类:
package
com.XiongYi.validationCode;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ValidationCode extends HttpServlet ... {
publicstaticStringgetValidationCodes(OutputStreamos)...{
charcodeTable[]=...{
'a','b','c','d','e','f','g','h','i','j','k','l',
'm','n','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L',
'M','N','P','Q','R','S','T','U','V','W','X','Y','Z',
'1','2','3','4','5','6','7','8','9'
};//判断时大小写不区分,另外,没有使用'O'和'0',也是怕混淆的麻烦
BufferedImageimage=newBufferedImage(60,20,
BufferedImage.TYPE_INT_RGB);
//生成60×20的RGB图片
Graphicsgraphic=image.getGraphics();
//背景色
graphic.setColor(newColor(0xDCDCDC));
graphic.fillRect(0,0,60,20);
charcodes[]=newchar[4];
//随机产生验证码
for(inti=0;i<=3;i++)...{
codes[i]=codeTable[(int)(codeTable.length*Math.random())];
}
//把字画上去
graphic.setColor(Color.BLACK);
graphic.setFont(newFont("Arial",Font.BOLD,16));
for(inti=0;i<=3;i++)...{
graphic.drawChars(codes,i,1,2+15*i,15+i);
//把codes[i]画到坐标为[10+5*i,15+i]的地方去
}
//15个干扰点
Randomrand=newRandom();
for(inti=0;i<15;i++)
graphic.drawOval(rand.nextInt(60),rand.nextInt(20),1,1);
//释放此图形的上下文并释放它所使用的所有系统资源
graphic.dispose();
try...{
ImageIO.write(image,"JPEG",os);
}catch(IOExceptione)...{
e.printStackTrace();
}
returnnewString(codes,0,codes.length);
}
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException...{
doPost(request,response);
}
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException...{
request.getSession().setAttribute("validationCodes",getValidationCodes(response.getOutputStream()));
}
}
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ValidationCode extends HttpServlet ... {
publicstaticStringgetValidationCodes(OutputStreamos)...{
charcodeTable[]=...{
'a','b','c','d','e','f','g','h','i','j','k','l',
'm','n','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L',
'M','N','P','Q','R','S','T','U','V','W','X','Y','Z',
'1','2','3','4','5','6','7','8','9'
};//判断时大小写不区分,另外,没有使用'O'和'0',也是怕混淆的麻烦
BufferedImageimage=newBufferedImage(60,20,
BufferedImage.TYPE_INT_RGB);
//生成60×20的RGB图片
Graphicsgraphic=image.getGraphics();
//背景色
graphic.setColor(newColor(0xDCDCDC));
graphic.fillRect(0,0,60,20);
charcodes[]=newchar[4];
//随机产生验证码
for(inti=0;i<=3;i++)...{
codes[i]=codeTable[(int)(codeTable.length*Math.random())];
}
//把字画上去
graphic.setColor(Color.BLACK);
graphic.setFont(newFont("Arial",Font.BOLD,16));
for(inti=0;i<=3;i++)...{
graphic.drawChars(codes,i,1,2+15*i,15+i);
//把codes[i]画到坐标为[10+5*i,15+i]的地方去
}
//15个干扰点
Randomrand=newRandom();
for(inti=0;i<15;i++)
graphic.drawOval(rand.nextInt(60),rand.nextInt(20),1,1);
//释放此图形的上下文并释放它所使用的所有系统资源
graphic.dispose();
try...{
ImageIO.write(image,"JPEG",os);
}catch(IOExceptione)...{
e.printStackTrace();
}
returnnewString(codes,0,codes.length);
}
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException...{
doPost(request,response);
}
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException...{
request.getSession().setAttribute("validationCodes",getValidationCodes(response.getOutputStream()));
}
}
然后,写一个Servlet将生成的图片写入页面:
package
com.XiongYi.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.XiongYi.validationCode.ValidationCode;
public class ValidationServlet extends HttpServlet ... {
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException...{
doPost(request,response);
}
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException...{
Stringstr=ValidationCode.getValidationCodes(response.getOutputStream());
request.getSession().setAttribute("validationCodes",str);
}
}
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.XiongYi.validationCode.ValidationCode;
public class ValidationServlet extends HttpServlet ... {
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException...{
doPost(request,response);
}
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException...{
Stringstr=ValidationCode.getValidationCodes(response.getOutputStream());
request.getSession().setAttribute("validationCodes",str);
}
}
接着,在login.jsp中加入如下表单:
<%
...
Stringpath=request.getContextPath();
StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
< form action ="<%=basePath+" servlet/LoginServlet"% > ">
< img src ="<%=basePath+" servlet/ValidationServlet"% > "/>
< br >
< input type ="text" name ="codes" />
< input type ="submit" />
</ form >
Stringpath=request.getContextPath();
StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
< form action ="<%=basePath+" servlet/LoginServlet"% > ">
< img src ="<%=basePath+" servlet/ValidationServlet"% > "/>
< br >
< input type ="text" name ="codes" />
< input type ="submit" />
</ form >
再写进行后台判断的Servlet:
package
com.XiongYi.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet ... {
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException...{
doPost(request,response);
}
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException...{
if(request.getSession().getAttribute("validationCodes").toString().toLowerCase()
.equals(request.getParameter("codes").toString().toLowerCase()))
response.getOutputStream().println("Right!");
else
response.getOutputStream().println("Wrong!");
}
}
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet ... {
publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException...{
doPost(request,response);
}
publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
throwsServletException,IOException...{
if(request.getSession().getAttribute("validationCodes").toString().toLowerCase()
.equals(request.getParameter("codes").toString().toLowerCase()))
response.getOutputStream().println("Right!");
else
response.getOutputStream().println("Wrong!");
}
}