SSM框架實(shí)現(xiàn)隨機(jī)生成驗(yàn)證碼登錄

用戶登錄時(shí),經(jīng)常會(huì)使用到驗(yàn)證碼,以下簡(jiǎn)單介紹一下驗(yàn)證碼的實(shí)現(xiàn)過程。
1、用戶登錄jsp

   <form action="<%=path%>/login/login.do" method="post">
        <input name="username" id="username" onclick="$('#error').val('');" type="text" class="yhm"/>
        <input name="password" type="password" id="password" onclick="$('#error').val('');" class="yhm pswd"/>
        <input type="text" name="code" onclick="$('#error').val('');" class="yzhengm"/><img id="img1" title="點(diǎn)擊獲取新驗(yàn)證碼" src="<%=path%>/verifycode/getVerifyCodeImage.do" onclick="changeimg()" width="62" height="28" alt="" style="display:inline-block;">
        <input type="submit" class="dengl" value=""/>
 </form>

上述頁面中,點(diǎn)擊驗(yàn)證碼可更新changeimg()方法js實(shí)現(xiàn)如下
先要引入jquery-3.3.1.min.js、將隨機(jī)字符轉(zhuǎn)化成圖片相關(guān)的DD_belatedPNG_0.0.8a-min.js。
然后在js代碼塊中需要引入DD_belatedPNG.fix('div, ul, img, li, input,p,ul,ol,h1,h2,h3,a,span,i');

<script type="text/javascript" src="<%=path %>/js/DD_belatedPNG_0.0.8a-min.js"></script>
<script type="text/javascript" src="<%=path %>/js/jquery-3.3.1.min.js"></script>
<script language="javascript" type="text/javascript">
        function changeimg(){
                var img=document.getElementById("img1");
                //防止頁面緩存
                img.src="<%=path%>/verifycode/getVerifyCodeImage.do"+ "?r="+Math.random();
            }
DD_belatedPNG.fix('div, ul, img, li, input,p,ul,ol,h1,h2,h3,a,span,i'); 
</script>

DD_belatedPNG_0.0.8a-min.js可在以下路徑下載。
https://pan.baidu.com/s/1_gKOFhjuzKrCX4NSt67evQ

2、登錄頁面加載和點(diǎn)擊驗(yàn)證碼時(shí),同時(shí)調(diào)用Controller類下的/verifycode/getVerifyCodeImage.do

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

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping(value = "/verifycode")
public class VerifyCodeController {

    /**
     * Controller Method
     */

    @RequestMapping(value = "/getVerifyCodeImage.do")
    public void getVerifyCodeImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 設(shè)置驗(yàn)證碼字符的字體和字號(hào)。
        Font mFont = new Font("Arial Black", Font.PLAIN, 22);

        //清除緩存,每次訪問該頁面時(shí)都從服務(wù)器端讀取
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        // 設(shè)置驗(yàn)證碼圖片的長度和高度。
        int width = 86, height = 40;
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);

        //畫圖畫板
        Graphics g = image.getGraphics();
        //定義一個(gè)隨機(jī)數(shù)
        Random random = new Random();
        //設(shè)置畫板背景顏色
//          g.setColor(getRandColor(200, 250));
        g.setColor(new Color(160, 177, 185));
        //設(shè)置畫板的填充范圍
        g.fillRect(1, 1, width - 1, height - 1);
//          g.setColor(new Color(102, 102, 102));
        g.drawRect(0, 0, width - 1, height - 1);
        //設(shè)置字體
        g.setFont(mFont);

        //顯示字符串,4位長度。
        String sRand = "";
        for (int i = 0; i < 4; i++) {
            String tmp = getRandomChar();
            sRand += tmp;
            //設(shè)置每個(gè)數(shù)字的顏色
            g.setColor(new Color(20 + random.nextInt(110), 20 + random
                    .nextInt(110), 20 + random.nextInt(110)));
            //在畫板上寫數(shù)字,起始位置
            g.drawString(tmp, 20 * i + 5, 27);
        }

        HttpSession session = request.getSession();
        // 把驗(yàn)證碼防到session中,用來前臺(tái)對(duì)比。
        session.setAttribute("verifycode", sRand.toLowerCase());
       // System.out.println(sRand.toLowerCase()+"--------------------------》");
        //顯示圖片
        g.dispose();
        //轉(zhuǎn)換成一張圖片,格式為JPEG
        ImageIO.write(image, "JPEG", response.getOutputStream());
    }

    /**
     * 隨機(jī)獲得顏色,RGB格式
     *
     * @param fc
     * @param bc
     * @return
     */
    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);
    }

    private String getRandomChar() {
        int rand = (int) Math.round(Math.random() * 2);
        long itmp = 0;
        char ctmp = '\u0000';
        switch (rand) {
            case 1:
                itmp = Math.round(Math.random() * 25 + 65);
                ctmp = (char) itmp;
                return String.valueOf(ctmp);
            case 2:
                itmp = Math.round(Math.random() * 25 + 97);
                ctmp = (char) itmp;
                return String.valueOf(ctmp);
            default:
                itmp = Math.round(Math.random() * 9);
                return String.valueOf(itmp);
        }
    }
}

上述實(shí)現(xiàn)類中,先隨機(jī)生成一個(gè)四位數(shù)的隨機(jī)數(shù)字+字母,然后將數(shù)字放到session中,最后使用ImageIO技術(shù)將隨機(jī)字符轉(zhuǎn)化成圖片。
3、重點(diǎn)來了,用戶登錄時(shí),需要校驗(yàn)用戶輸入的驗(yàn)證碼是否與實(shí)際驗(yàn)證碼一致
LoginController.class實(shí)現(xiàn):

 public String login(User user){
        if(StringUtils.isEmpty(user.getUsername())){
            request.setAttribute("error","用戶名不能為空!");
            return "index";
        }
        if(StringUtils.isEmpty(user.getPassword())){
            request.setAttribute("error","密碼不能為空!");
            return "index";
        }
        String vcode =(String)request.getSession().getAttribute("verifycode");
        if(!user.getCode().equalsIgnoreCase(vcode)){
            request.setAttribute("error","驗(yàn)證碼錯(cuò)誤!");
            return "index";
        }

        request.setAttribute("username",user.getUsername());
        return loginService.checkUser(request,user);
    }

上述loginService.checkUser()的實(shí)現(xiàn)可參考“SSM框架新增/修改用戶、用戶登錄時(shí)密碼加密處理及校驗(yàn)http://www.itdecent.cn/p/d9773ec61661”一文。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1.ios高性能編程 (1).內(nèi)層 最小的內(nèi)層平均值和峰值(2).耗電量 高效的算法和數(shù)據(jù)結(jié)構(gòu)(3).初始化時(shí)...
    歐辰_OSR閱讀 30,260評(píng)論 8 265
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,586評(píng)論 19 139
  • 離婚那年我20歲,孩子才兩個(gè)多月。狠心的離開是有不得已的苦衷,為自己愚昧的執(zhí)著,承受了該有的苦果,最終還是選擇默默...
    喜暮雨閱讀 458評(píng)論 1 0
  • 參加了一個(gè)微信群讀書打卡活動(dòng):把這一個(gè)星期的打卡整理如下 非暴力溝通模式1.誠實(shí)地表達(dá)自己,而不批評(píng)、指責(zé)(1)觀...
    君途漫漫閱讀 318評(píng)論 1 0
  • 人生有很多種活法,我偏偏選擇了最沒意義的一種,所以想寫點(diǎn)東西,不為什么,就想審視自己,讓自己再次擁有內(nèi)心!
    幽幽思閱讀 260評(píng)論 0 0

友情鏈接更多精彩內(nèi)容