1. 程式人生 > >兩種驗證碼的實現程式碼

兩種驗證碼的實現程式碼

第一種是用Servlet實現驗證碼:


程式碼如下:

public class CodeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String codes="abcdefghijklmnopqrstuvwxyzABCDEFJHIJKLMNOPQRSTUVWXYZ0123456789";    
        BufferedImage img=new BufferedImage(80,30,BufferedImage.TYPE_3BYTE_BGR);
        Graphics g=img.getGraphics();
        //填充圖片
        g.setColor(new Color(255,255,255));
        g.fillRect(0, 0, 80, 30);
        //畫入五個隨機數
        Random rm=new Random();
        StringBuffer sb=new StringBuffer();
        for(int i=0;i<5;i++){
            int index=rm.nextInt(codes.length());
            char code=codes.charAt(index);
            g.setColor(new Color(rm.nextInt(256),rm.nextInt(256),rm.nextInt(256)));
            g.setFont(new Font("宋體", Font.BOLD, 25));
            g.drawString(code+"", 2+15*i, 22);
            sb.append(code);
        }
        
        //畫干擾線
        for(int i=0;i<10;i++){
            g.setColor(new Color(rm.nextInt(256),rm.nextInt(256),rm.nextInt(256)));
            g.drawLine(rm.nextInt(100), rm.nextInt(50), rm.nextInt(100), rm.nextInt(50));
        }
        
        //將驗證碼圖片回寫給瀏覽器
        response.setContentType("image/jpeg;charset=utf-8");
        OutputStream out=response.getOutputStream();
        ImageIO.write(img, "jpeg", out);
        
        //將隨機字串儲存在session中
        request.getSession().setAttribute("code", sb.toString());
    }

}

第二中方法在前臺jsp頁面畫圖:

<%@ page contentType="image/jpeg" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*" pageEncoding="utf-8"%>
<%!
Color getRandColor(int fc,int bc)
{
Random random = new Random();
if(fc>255) fc=255;
if(bc>255) bc=255;
int r=fc+random.nextInt(bc-fc);
int g=fc+random.nextInt(bc-fc);
int b=fc+random.nextInt(bc-fc);
return new Color(r,g,b);
}
%>
<%
out.clear();                           /*這句針對resin伺服器,如果是tomacat可以不要這句*/
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);
int width=60, height=20;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200,250));
g.fillRect(0, 0, width, height);
g.setFont(new Font("Times New Roman",Font.PLAIN,18));
g.setColor(getRandColor(160,200));
for (int i=0;i<155;i++)
{
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(12);
int yl = random.nextInt(12);
g.drawLine(x,y,x+xl,y+yl);
}
String sRand="";
for (int i=0;i<4;i++){
String rand=String.valueOf(random.nextInt(10));
sRand+=rand;
g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
g.drawString(rand,13*i+6,16);
}
// 將認證碼存入SESSION
session.setAttribute("sRand",sRand);
g.dispose();
ImageIO.write(image, "JPEG", response.getOutputStream());
%>

第一種:image.jsp
<script type="text/javascript">
         function loadImage(){
         document.getElementById("randImage").src = "${pageContext.request.contextPath}/image.jsp?"+Math.random(); //Math.random()方法非常重要,它使每次的請求都不同以便重新發送。如果每次的請求都一樣,那麼不會重新生成頁面
         }
      </script>



 <img onClick="javascript:loadImage();"  title="換一張試試" id="randImage"
                          src="${pageContext.request.contextPath}/image.jsp"  border="1" >




第二種:servlet方式
 <servlet-name>CodeServlet</servlet-name>
    <servlet-class>com.yinhe.web.servlet.CodeServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>CodeServlet</servlet-name>
    <url-pattern>/checkCode</url-pattern>
  </servlet-mapping>



<img src="checkCode" alt="" id="codeImg"
style="width: 80px; height: 30px; border: 1px solid black;" />
<a href="javascript:;" onclick="document.getElementById('codeImg').src = 'checkCode?'+(new Date()).getTime()">換一張</a>
<span id="codemsg" style="color: red; font-size: 20px;"></span>