1. 程式人生 > >在頁面上生成動態圖片驗證碼

在頁面上生成動態圖片驗證碼

這兩種方式都得把驗證碼存入session當中,然後提交表單時進行才能進行校驗,因為都是以img src 方式生成的圖片驗證碼,沒法在前臺進行驗證,或許是我不會,有人想到解決辦法的麻煩告我一聲.

 

1.引入jsp方式

先建立一個jsp檔案,下面這段jsp,其實就是在jsp上寫java程式碼來畫一個驗證碼圖片,然後把生成的驗證碼存入session當中,然後在後臺就可以通過session來獲取到驗證碼進行驗證.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.util.Random"%>
<%@ page import="java.io.OutputStream"%>
<%@ page import="java.awt.Color"%>
<%@ page import="java.awt.Font"%>
<%@ page import="java.awt.Graphics"%>
<%@ page import="java.awt.image.BufferedImage"%>
<%@ page import="javax.imageio.ImageIO"%>
<%
   int width = 80;
   int height = 32;
   //create the image
   BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
   Graphics g = image.getGraphics();
   // set the background color
   g.setColor(new Color(0xDCDCDC));
   g.fillRect(0, 0, width, height);
   // draw the border
   g.setColor(Color.black);
   g.drawRect(0, 0, width - 1, height - 1);
   // create a random instance to generate the codes
   Random rdm = new Random();
   String hash1 = Integer.toHexString(rdm.nextInt());
   // make some confusion
   for (int i = 0; i < 50; i++) {
      int x = rdm.nextInt(width);
      int y = rdm.nextInt(height);
      g.drawOval(x, y, 0, 0);
   }
   // generate a random code
   String capstr = hash1.substring(0, 4);
   session.setAttribute("key", capstr);    //把生成的驗證碼存入session當中
   g.setColor(new Color(0, 100, 0));
   g.setFont(new Font("Candara", Font.BOLD, 24));
   g.drawString(capstr, 8, 24);
   g.dispose();
   response.setContentType("image/jpeg");
   out.clear();
   out = pageContext.pushBody();
   OutputStream strm = response.getOutputStream();
   ImageIO.write(image, "jpeg", strm);
   strm.close();
%>

這個就是img標籤,只需要把src裡面的路徑改為上面jsp存放的路徑就可以了,單擊事件是為了每次點選圖片生成新的驗證碼.

<img style="height: 100%;width: 100%" id="loginform:vCode" src="${pageContext.request.contextPath }/jsps/validatecode.jsp" onclick="javascript:document.getElementById('loginform:vCode').src='${pageContext.request.contextPath }/jsps/validatecode.jsp?'+Math.random();" />

 2.通過訪問controller方式在後臺生成圖片驗證碼來寫到前臺

先寫兩個工具類

生成隨機數的

package com.bgs.utils;

public class RandomNumberUtil {

    public static String getRandomNumber4(){
        String code = "";
        for(int i=0;i<4;i++){
            int random = (int)(Math.random()*10);
            code += String.valueOf(random);
        }
        return code;
    }

    public static String getRandomNumber6(){
        String code = "";
        for(int i=0;i<6;i++){
            int random = (int)(Math.random()*10);
            code += String.valueOf(random);
        }
        return code;
    }
}

生成圖片的  這個生成圖片的需要傳入一個字串進去

package com.bgs.utils;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class ImageVerifyCodeUtil {

    public static BufferedImage getBufferedImage(String capstr){
        int width = 80;
        int height = 32;
        //create the image
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        // set the background color
        g.setColor(new Color(0xDCDCDC));
        g.fillRect(0, 0, width, height);
        // draw the border
        g.setColor(Color.black);
        g.drawRect(0, 0, width - 1, height - 1);
        g.setColor(new Color(0, 100, 0));
        g.setFont(new Font("Candara", Font.BOLD, 24));
        g.drawString(capstr, 8, 24);
        g.dispose();
        return image;
    }


}

 controller

//生成圖片驗證碼的方法
@RequestMapping("/findVerifyPictureCode")
public void findVerifyPictureCode(HttpSession session, HttpServletResponse response){
    //告訴客戶端,輸出的格式
    response.setContentType("image/jpeg");
    String randomNumber4 = RandomNumberUtil.getRandomNumber4();    //生成隨機數
    BufferedImage bufferedImage = ImageVerifyCodeUtil.getBufferedImage(randomNumber4);  把隨機數傳入生成圖片
    try {
        ImageIO.write(bufferedImage, "JPG", response.getOutputStream());  //把圖片寫回到前臺
        session.setAttribute("randomCode",randomNumber4);     //將生成的驗證碼存入session
    } catch (IOException e) {
        e.printStackTrace();
    }

} 

前臺程式碼,記得把src中的路徑改為訪問controller的路徑

<img id="servletImg" src="${pageContext.request.contextPath}/managerUser/findVerifyPictureCode" onclick="javascript:changImg()"/>
<script type="text/javascript">
    function changImg(){
        var img = document.getElementById("servletImg");
        var d = new Date();
        var time = d.getTime();//如果沒有這個
        //下面這一句不會起作用,因為瀏覽器的快取技術,圖片並不會重新整理
        //img.src="/myHelloWeb/servlet/ImageServlet";
        img.src="${pageContext.request.contextPath}/managerUser/findVerifyPictureCode?"+time;
        //?號後面的東西是通過get方式傳遞的
    }

</script>