java 理解如何實現圖片驗證碼 傻瓜都能看懂。

先代碼後解釋:java

只要把代碼複製到你的項目中就能夠了。session

代碼:架構

驗證碼工具類:app

package cn.happy.util.imagesVerTion;

/**
 * Author: SamGroves
 *
 * Description: 驗證碼生成器
 *
 * Date: 2017/8/29
 */
import javax.servlet.http.HttpServletRequest;
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 Captcha {
    private static char mapTable[] = {
            '0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', '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, 18));
        // 隨機產生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, 13 * i + 20, 25);
        }
        // 釋放圖形上下文
        g.dispose();
        returnMap.put("image",image);//把驗證碼的圖片放到了map集合中。
        returnMap.put("strEnsure",strEnsure);//把驗證碼的文字放入到了map集合中。
       /* request.getSession().setAttribute("strEnsure",strEnsure);*/
        System.out.println(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);
    }
}

controller:dom

  @RequestMapping(value = "/captcha")
    @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 = Captcha.getImageCode(86, 37, os);
        String simpleCaptcha = "simpleCaptcha";
        request.getSession().setAttribute("simpleCaptcha", map.get("strEnsure").toString().toLowerCase());
        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;
    }




        @RequestMapping(value = "/verify")
        @ResponseBody
        public String checkcode(HttpServletRequest request,
                                HttpSession session,
                                String checkCode) throws Exception {

            checkCode=(String) request.getSession().getAttribute("simpleCaptcha");

            // 得到驗證碼對象
           /* Object cko = session.getAttribute("simpleCaptcha");*/
            String cko = request.getParameter("checkcode01");

            if (cko == null ||cko=="") {
                request.setAttribute("errorMsg", "請輸入驗證碼!");
                System.out.println("驗證碼是空格的啊");
                return "請輸入驗證碼!";
            }
            String captcha = cko.toString();//文本框輸入的驗證碼
            // 判斷驗證碼輸入是否正確
            Date now = new Date();
            Long codeTime = Long.valueOf(session.getAttribute("codeTime") + "");
            if (StringUtils.isEmpty(checkCode) || captcha == null || !(checkCode.equalsIgnoreCase(captcha))) {
                request.setAttribute("errorMsg", "驗證碼錯誤!");
                System.out.println("驗證碼錯的呀");
                return "驗證碼錯誤,請從新輸入!";

                // 驗證碼有效時長爲1分鐘

            } else if ((now.getTime() - codeTime) / 1000 / 60 > 1) {
                request.setAttribute("errorMsg", "驗證碼已失效,請從新輸入!");
                System.out.println("驗證碼時間太長了");
                return "驗證碼已失效,請從新輸入!";
            } else {

                // 在這裏能夠處理本身須要的事務,好比驗證登錄等
                System.out.println("驗證碼輸入正確");
                return "驗證經過!";
            }
        }

架構:工具

 

 

 

 

 

解釋:post

首先來看工具類:  工具類反正像我這種我是看不懂的,   若是你也看不懂 須要關注工具類的幾個點就能夠了。 他這個工具類已經寫好了,咱們須要關心的就是這個驗證碼圖片中的數字。字體

可能你不知道怎麼去map集合中拿出來使用。  不用擔憂,他在controller中的代碼已經拿出來了。 spa

 

 咱們主要在下面這個分支作操做。code

頁面:

文本框:

驗證碼圖片:

相關文章
相關標籤/搜索