後臺驗證碼

廢話不多說,直接上代碼。先看看文件的位置

ValidateCodeServlet.java

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.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class ValidataCoed
 */
@WebServlet("/ValidataCoed")
public class ValidateCodeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ValidateCodeServlet() {
        super();
        // TODO Auto-generated constructor stub
    }


    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        this.doPost(request, response);
    }
    public  Color getRandomColor(int fc,int bc){
        Random random = new Random();
        Color randomColor = null;
        if(fc>255) fc=255;
        if(bc>255) bc=255;
        //設置個0-255之間的隨機顏色值
        int r=fc+random.nextInt(bc-fc);
        int g=fc+random.nextInt(bc-fc);
        int b=fc+random.nextInt(bc-fc);
        randomColor = new Color(r,g,b);
        return randomColor;//返回具有指定紅色、綠色和藍色值的不透明的 sRGB 顏色
    }
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //禁止頁面緩存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "No-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");      //設置響應正文的MIME類型爲圖片
        int width=60, height=20;  
        /**創建一個位於緩存中的圖像,寬度60,高度20 */  
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);     
        Graphics g = image.getGraphics();           //獲取用於處理圖形上下文的對象,相當於畫筆
        Random random = new Random();               //創建生成隨機數的對象
        g.setColor(getRandomColor(200,250));        //設置圖像的背景色
        g.fillRect(0, 0, width, height);            //畫一個矩形 ,座標(0,0),寬度60,高度20 
        g.setFont(new Font("Times New Roman",Font.PLAIN,18));   //設定字體格式
        g.setColor(getRandomColor(160,200));
        for(int i=0;i<130;i++){                     //產生130條隨機干擾線
            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);              //在圖象的座標(x,y)和座標(x+x1,y+y1)之間畫干擾線 
        } 
        String strCode="";  
        for (int i=0;i<4;i++){   
            String strNumber=String.valueOf(random.nextInt(10)); //把隨機數轉換成String字符串
            strCode=strCode+strNumber;
            //設置字體的顏色
            g.setColor(new Color(15+random.nextInt(120),15+random.nextInt(120),15+random.nextInt(120)));
            g.drawString(strNumber,13*i+6,16);       //將驗證碼依次畫到圖像上,座標(x=13*i+6,y=16)
        }
        request.getSession().setAttribute("Code",strCode);          //把驗證碼保存到Session中   
        g.dispose();  //釋放此圖像的上下文以及它使用的所有系統資源
        ImageIO.write(image, "JPEG", response.getOutputStream());   //輸出JPEG格式的圖像    
        response.getOutputStream().flush();                         //刷新輸出流 
        response.getOutputStream().close();                         //關閉輸出流 
    }

}

配置的XML是在上一篇的基礎上進行的配置:

<?xml version="1.0" encoding="GBK"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>MyBlog</display-name>
  <servlet>
    <servlet-name>RegServlet</servlet-name>
    <servlet-class>servlet.RegServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>RegServlet</servlet-name>
    <url-pattern>/RegServlet</url-pattern>
  </servlet-mapping>
  <servlet>
  <servlet-name>ValidateCodeServlet</servlet-name>
  <servlet-class>servlet.ValidateCodeServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  <servlet-name>ValidateCodeServlet</servlet-name>
  //這裏的url將會是後面驗證碼的src的來源
  <url-pattern>/ValidateCodeServlet</url-pattern>
  </servlet-mapping>


</web-app>

index.jsp

//在上次的基礎上添加了兩行代碼:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>府城的博客</title>
</head>
<body>
    <form action ="RegServlet" method="Post" onsubmit="return reg(this);">
        <table align="center" border="0", width="500">
        <tr>
           <td align ="right" width ="30%">用戶名:</td>
           <td><input type ="text" name ="username" class="box"></td>           
        </tr>
         <tr>
           <td align ="right" width ="30%">密碼:</td>
           <td><input type ="text" name ="password" class="box"></td>           
        </tr>
         <tr>
           <td align ="right" width ="30%">性別:</td>
           <td><input type ="radio" name ="sex" value="男" checked="checked"><input type ="radio" name ="sex" value="女" ></td>           
        </tr>
         <tr>
           <td align ="right" width ="30%">密碼找回問題:</td>
           <td><input type ="text" name ="question" class="box"></td>           
        </tr>
        <tr>
           <td align ="right" width ="30%">密碼找回答案:</td>
           <td><input type ="text" name ="answer" class="box"></td>           
        </tr>
        <tr>
           <td align ="right" width ="30%">郵箱:</td>
           <td><input type ="text" name ="email" class="box"></td>           
        </tr>
         <tr>
                <td>驗證碼:</td>
                <td>
                    <img alt="" src="ValidateCodeServlet" >
                </td>
            </tr>
            <tr>
                <td>輸入驗證碼:</td>
                <td>
                    <input type="text" name="code"/>
                </td>
            </tr>
        <tr>
            <td colspan="2" align="center" height="40">
            <input type ="submit" value="註冊">
            <input type ="reset" value="重置">
            </td>
        </tr> 


</body>
</html>

然後就成功了

這裏我沒有加驗證輸入的正確性,很簡單的邏輯就不說了。以及如何將四位數字驗證碼變成字母加數字,無非是ASCLL碼的範圍。

發佈了36 篇原創文章 · 獲贊 51 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章