J2EE動態生成驗證碼可刷新

1、使用servlet生成驗證碼
servlet:CodeMakerServlet.java

----------------------------------------------
package com.free.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CodeMakerServlet extends HttpServlet
{
      /**
  *
  */
 private static final long serialVersionUID = 1L;
 
 //生成隨機類
    Random random = new Random();
   
 //驗證碼字體
    private Font[] codeFont =
    {
        new Font("Times New Roman", Font.PLAIN,18),
        new Font("Times New Roman", Font.PLAIN, 18),
        new Font("Times New Roman", Font.PLAIN,18),
        new Font("Times New Roman", Font.PLAIN, 18)
    };
    //驗證碼數字顏色
    private Color[] color =
    {
       Color.BLACK, Color.RED, Color.DARK_GRAY, Color.BLUE
    };

    String codeNumbers = "";

    int width = 60, height = 20;

    // 處理 HTTP get 請求
    public void doGet(HttpServletRequest request, HttpServletResponse response)
                      throws ServletException, IOException
    {
     System.out.println("生成驗證碼");
        // 清空緩衝區
        response.reset();

        // 注意這裏的MIME類型
        response.setContentType("image/png");

        // 設置頁面不緩存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        // 創建一個圖像,驗證碼顯示的圖片大小
        BufferedImage image = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB);

        // 獲取圖形上下文
        Graphics g = image.getGraphics();
       
        // 設置背景
        g.setColor(getRandColor(200,250));
        g.fillRect(0, 0, width, height);

        for (int i = 0; i < 4; i++)
        {
            drawCode(g, i);
        }
        //添加干擾線
        drawNoise(g, 12);

        // 繪製邊框
        //g.setColor(Color.gray);
        //g.drawRect(0, 0, width - 1, height - 1);

        // 將驗證碼內容保存進session中,用於驗證用戶輸入是否正確時使用
        HttpSession session = request.getSession(true);
        session.removeAttribute("rand");
        session.setAttribute("rand", codeNumbers);
        // 重設字符串
        codeNumbers = "";
        // 利用ImageIO類的write方法對圖像進行編碼
        ServletOutputStream sos = response.getOutputStream();
        ImageIO.write(image, "PNG", sos);
        sos.close();
    }

    // 繪製驗證碼
    public void drawCode(Graphics graphics, int i)
    {
        String number = String.valueOf(random.nextInt(10));
        graphics.setFont(codeFont[i]);
        graphics.setColor(color[i]);
        //繪製驗證碼到圖片X、Y
        graphics.drawString(number, 6 + i * 13,16);

        codeNumbers += number;
    }

    // 繪製干擾線
    public void drawNoise(Graphics graphics, int lineNumber)
    {
        graphics.setColor(getRandColor(160,200));
        for (int i = 0; i < lineNumber; i++)
        {
            int pointX1 = 1 + (int)(Math.random() * width);
            int pointY1 = 1 + (int)(Math.random() * height);
            int pointX2 = 1 + (int)(Math.random() * width);
            int pointY2 = 1 + (int)(Math.random() * height);
            graphics.drawLine(pointX1, pointY1, pointX2, pointY2);
        }
    }
    public 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);
 }
    // 處理 HTTP post 請求, 和doGet一樣
    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        doGet(request, response);
    }
}

----------------------------------------------
調用頁面code1.jsp
----------------------------------------------
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>servlet生成驗證碼</title>
   
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
 <script type="text/javascript">
  function refreshcode(){
   document.getElementById("code").src="servlet/CodeMakerServlet?a="+Math.random()+100;
   return false;
  }
 </script>
  </head>
 
  <body>
   (servlet頁面生成驗證碼)<br/><br/>
   <form method=post action="check.jsp">
   用戶名:<input type="text" name="userName" size="15" value=""><br>
 密碼:<input type="text" name="password" size="15" value=""><br>
   驗證碼:<input type="text" size="4" maxlength="4" name="rand"/>
    <img id="code" src="servlet/CodeMakerServlet" title="看不清點擊刷新驗證碼" style="cursor : pointer;"  onclick="return refreshcode()"/>
   <input type=submit value="提交">
   </form>
  </body>
</html>
----------------------------------------------

2、代碼寫在JSP頁面
生成驗證碼頁面image.jsp

----------------------------------------------


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ page contentType="image/jpeg" import="java.awt.*,
java.awt.image.*,java.util.*,javax.imageio.*" %>
<%!
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);
}
%>
<%
//設置頁面不緩存
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(new Color());
//g.drawRect(0,0,width-1,height-1);

// 隨機產生155條幹擾線,使圖象中的認證碼不易被其它程序探測到
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);
}

// 取隨機產生的認證碼(4位數字)
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("rand",sRand);

// 圖象生效
g.dispose();

// 輸出圖象到頁面
ImageIO.write(image, "JPEG", response.getOutputStream());
%>

----------------------------------------------
調用頁面code2.jsp
----------------------------------------------
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ page contentType="text/html;charset=gb2312" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>JSP頁面生成驗驗證碼</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="0">

<script type="text/javascript">
  function refreshcode(){
   document.getElementById("code").src="image.jsp?a="+Math.random()+100;
   return false;
  }
 </script>
</head>
<body>
 <form method=post action="check.jsp">
  (JSP頁面生成驗證碼)<br/><br/>
  用戶名:<input type="text" name="userName" size="15" value=""><br>
  密碼:<input type="text" name="password" size="15" value=""><br>
  驗證碼:<input type="text" name="rand" maxlength="4" size="4" value="">
  <img id="code" border=0 src="image.jsp" onclick="refreshcode()">
  <input type=submit value="提交">
 </form>
</body>
</html>

----------------------------
驗證頁面check.jsp
----------------------------------------------
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<html>
<head>
<title>認證碼驗證頁面</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="0">
</head>

<body>
<%
String rand = (String)session.getAttribute("rand");
String input = request.getParameter("rand");
%>
系統產生的認證碼爲: <%= rand %><br>
您輸入的認證碼爲: <%= input %><br>
<br>
<%
if (rand.equals(input)) {
%>
<font color=green>輸入相同,認證成功!</font>
<%
} else {
%>
<font color=red>輸入不同,認證失敗!</font>
<%
}
//使用完成後清除session
session.removeAttribute("rand");
%>
</body>
</html>
----------------------------------------------
servlet在web.xml中的配置
----------------------------------------------
<servlet>
    <servlet-name>CodeMakerServlet</servlet-name>
    <servlet-class>com.free.util.CodeMakerServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>CodeMakerServlet</servlet-name>
    <url-pattern>/servlet/CodeMakerServlet</url-pattern>
  </servlet-mapping>
----------------------------------------------

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章