圖片驗證碼生成並驗證驗證碼


package com.zy.handle;

/**
 * Author
 * <p>
 * Description: 驗證碼生成器 工具類
 * <p>
 * Date: 2017/8/29
 */

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class CaptchaUtil {
    private static char mapTable[] = {
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
            'N', 'O', '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', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
    };

    public static Map<String, Object> getImageCode(int width, int height, OutputStream os) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        if (width <= 0) width = 60;
        if (height <= 0) 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, 24));
        // 隨機產生168條干擾線,使圖象中的認證碼不易被其它程序探測到
        g.setColor(getRandColor(160, 200));
        for (int i = 0; i < 168; 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 strEnsure = "";
        //4代表4位驗證碼,如果要生成更多位的認證碼,則加大數值
        for (int i = 0; i < 4; ++i) {
            strEnsure += mapTable[(int) (mapTable.length * Math.random())];
            // 將認證碼顯示到圖象中
            g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
            // 直接生成
            String str = strEnsure.substring(i, i + 1);
            // 設置隨便碼在背景圖圖片上的位置
            g.drawString(str, 17 * i + 20, 25);
        }
        // 釋放圖形上下文
        g.dispose();
        returnMap.put("image", image);
        returnMap.put("strEnsure", strEnsure);
        return returnMap;
    }

    //給定范圍獲得隨機顏色
    static 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);
    }
}
package com.zy.handle.market.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zy.handle.CaptchaUtil;

/**
 * 驗證碼
 */
@Controller
@RequestMapping("/captcha")
public class CaptchaController {

  String simpleCaptcha = "captcha";

  /**
   * 用於生成帶四位數字驗證碼的圖片
   */
  @RequestMapping(value = "/get")
  @ResponseBody
  public String imagecode(HttpServletRequest request, HttpServletResponse response) throws Exception {
    response.setDateHeader("Expires", 0);
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    response.setHeader("Pragma", "no-cache");
    response.setContentType("image/jpeg");

    OutputStream os = response.getOutputStream();
    // 返回驗證碼和圖片的map
    Map<String, Object> map = CaptchaUtil.getImageCode(96, 36, os);

    request.getSession().setAttribute(simpleCaptcha, map.get("strEnsure").toString());
    request.getSession().setAttribute("codeTime", new Date().getTime());
    try {
      ImageIO.write((BufferedImage) map.get("image"), "jpg", os);
    } catch (IOException e) {
      return "";
    } finally {
      if (os != null) {
        os.flush();
        os.close();
      }
    }
    return null;
  }

  /**
   * @param checkCode 前端用戶輸入返回的驗證碼 參數若需要,自行添加
   */
  @RequestMapping(value = "/verify")
  @ResponseBody
  public String checkcode(HttpServletRequest request, String checkCode) {
    HttpSession session = request.getSession();
    // 獲得驗證碼對象
    Object cko = session.getAttribute(simpleCaptcha);
    if (cko == null) {
      request.setAttribute("errorMsg", "請輸入驗證碼!");
      return "請輸入驗證碼!";
    }
    String captcha = cko.toString();

    // 判斷驗證碼輸入是否正確
    if (StringUtils.isEmpty(checkCode) || captcha == null || !(checkCode.equalsIgnoreCase(captcha))) {
      request.setAttribute("errorMsg", "驗證碼錯誤!");
      return "驗證碼錯誤,請重新輸入!";
    } else {
      // 驗證碼有效時長為1分鍾
      Date now = new Date();
      Long codeTime = Long.valueOf(session.getAttribute("codeTime") + "");
      if ((now.getTime() - codeTime) / 1000 / 60 > 2) {
        request.setAttribute("errorMsg", "驗證碼已失效,請重新輸入!");
        return "驗證碼已失效,請重新輸入!";
      } else {
        // 在這里可以處理自己需要的事務,比如驗證登陸等
        return "1";
      }
    }
  }

  public void removeCode(HttpServletRequest request, String checkCode) {
    HttpSession session = request.getSession();
    Object cko = session.getAttribute(simpleCaptcha);
    if (cko == null) {
      return;
    }
    if (StringUtils.equals(checkCode, cko.toString())) {
      session.removeAttribute(simpleCaptcha);
    }
  }
}
@RequestMapping("/list")
  @ResponseBody
  public SimpleJsonResult search(HttpServletRequest request, Cadastre cadastre, String captcha) {

    if (StringUtils.isBlank(captcha)) {
      return failureJsonResult("驗證碼不能為空");
    }

    String checkResult = captchaController.checkcode(request, captcha);
    if (!"1".equals(checkResult)) {
      return failureJsonResult(checkResult);
    }
    // 移除驗證碼,防止重復使用
    captchaController.removeCode(request, captcha);
    return successJsonResult(cadastreService.list(cadastre));
  }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM