JavaEE----登陸界面驗證碼實現

来源:https://www.cnblogs.com/tmlh/archive/2018/07/14/9311150.html
-Advertisement-
Play Games

主要使用後端驗證,調用awt API ,會簡單調用即可,繪圖代碼已封裝到LoginVerifyUtils中。 界面展示: LoginVerifyUtils全部代碼 1 import java.awt.Color; 2 import java.awt.Font; 3 import java.awt.G ...


主要使用後端驗證,調用awt API ,會簡單調用即可,繪圖代碼已封裝到LoginVerifyUtils中。


界面展示:

 

 

LoginVerifyUtils全部代碼

 1 import java.awt.Color;
 2 import java.awt.Font;
 3 import java.awt.Graphics2D;
 4 import java.awt.font.FontRenderContext;
 5 import java.awt.geom.Rectangle2D;
 6 import java.awt.image.BufferedImage;
 7 import java.io.ByteArrayOutputStream;
 8 import java.io.IOException;
 9 import java.util.Random;
10 
11 import javax.imageio.ImageIO;
12 
13 public class LoginVerifyUtils {
14 
15     private static LoginVerifyUtils loginVerifyUtils = new LoginVerifyUtils(); 
16 
17     private LoginVerifyUtils() {
18     }
19     
20     public static LoginVerifyUtils getInstance() {
21         return loginVerifyUtils;
22     }
23     
24     /**
25      * 繪畫驗證碼
26      * @param output
27      * @return
28      */
29     public String drawImg(ByteArrayOutputStream output) {
30         String code = "";
31         // 隨機產生4個字元
32         for (int i = 0; i < 4; i++) {
33             code += randomChar();
34         }
35         int width = 70;
36         int height = 25;
37         BufferedImage bi = new BufferedImage(width, height,
38                 BufferedImage.TYPE_3BYTE_BGR);
39         Font font = new Font("Times New Roman", Font.PLAIN, 20);
40         // 調用Graphics2D繪畫驗證碼
41         Graphics2D g = bi.createGraphics();
42         g.setFont(font);
43         Color color = new Color(66, 2, 82);
44         g.setColor(color);
45         g.setBackground(new Color(226, 226, 240));
46         g.clearRect(0, 0, width, height);
47         FontRenderContext context = g.getFontRenderContext();
48         Rectangle2D bounds = font.getStringBounds(code, context);
49         double x = (width - bounds.getWidth()) / 2;
50         double y = (height - bounds.getHeight()) / 2;
51         double ascent = bounds.getY();
52         double baseY = y - ascent;
53         g.drawString(code, (int) x, (int) baseY);
54         g.dispose();
55         try {
56             ImageIO.write(bi, "jpg", output);
57         } catch (IOException e) {
58             e.printStackTrace();
59         }
60         return code;
61     }
62     
63     /**
64      * 隨機獲取一個字元
65      * @return
66      */
67     public char randomChar() {
68         Random r = new Random();
69         String s = "ABCDEFGHJKLMNPRSTUVWXYZ0123456789";
70         return s.charAt(r.nextInt(s.length()));
71     }
72 }
View Code

 

login.jsp

<div  id="login">
    <div class="form-inline"  >

        <div class="input-group">
            <span class="input-group-addon">賬號</span>
            <input type="text" class="form-control" name="id" id="adminId">
        </div><br/><br/>
        
        <div class="input-group">
            <span class="input-group-addon">密碼</span>
            <input type="password" class="form-control" name="passwd" id="passwd">
        </div>
        
        <br/><br/>
         <div class="input-group">
             <span class="code_img"> <img
                        src="${APP_PATH}/admin/getVerifyCode"
                        width="110" height="40" id="verifyCodeImage">

                    </span><a id="changeVerifImageRegister"
                        onclick="javascript:changeImage();">換一張</a>
        </div> 
        
        <br/><br/>
         <div class="input-group">
            <span class="input-group-addon">驗證碼</span>
            <input type="text" class="form-control" name="verifyCode" style="width: 184px" id="verifyCode">
        </div><br/> 
        
        <p style="text-align: right;color: red;position: absolute" id="info"></p>
        
        <br/>
        <button id="loginButton"  class="btn btn-primary">登陸
        </button>

    </div>
View Code

 

依賴ui庫

    <link rel="stylesheet" href="${APP_PATH }/static/css/bootstrap.min.css">
    <script src="${APP_PATH }/static/js/jquery-3.2.1.min.js"></script>
    <script src="${APP_PATH }/static/js/bootstrap.min.js"></script>

 

javascript

 $("#loginButton").click(function () {
            if($("#adminId").val()==''&&$("#passwd").val()==''){
                $("#info").text("提示:賬號和密碼不能為空");
            }
            else if ($("#adminId").val()==''){
                $("#info").text("提示:賬號不能為空");
            }
            else if($("#passwd").val()==''){
                $("#info").text("提示:密碼不能為空");
            }else if($("#verifyCode").val()==''){
                $("#info").text("提示:請輸入驗證碼");
            }
            else {
                //驗證碼
                $.ajax({
                    type: "GET",
                    url: "${APP_PATH}/admin/verifyCode",
                    data: {
                        verifyCode:$("#verifyCode").val() ,
                    },
                    dataType: "json",
                    success: function(data) {
                        if(data.stateCode.trim() == "1003") {
                            $("#info").text("提示:伺服器異常");
                            flag = false;
                        } else if(data.stateCode.trim() == "1002") {
                            $("#info").text("提示:驗證碼錯誤");
                        } else{
                            userLogin()
                        }
                    } 
                });
                
            }
        })
        function userLogin(){
            $.ajax({
                type: "POST",
                url: "${APP_PATH}/admin/login",
                data: {
                    username:$("#adminId").val() ,
                    password: $("#passwd").val()
                },
                dataType: "json",
                success: function(data) {
                    if(data.stateCode.trim() == "1003") {
                        $("#info").text("提示:該用戶不存在");
                    } else if(data.stateCode.trim() == "1002") {
                        $("#info").text("提示:密碼錯誤");
                    } else if(data.stateCode.trim() == "1001"){
                        $("#info").text("提示:登陸成功,跳轉中...");
                        window.location.href="${APP_PATH}/main";
                    }else{
                        $("#info").text("提示:伺服器出錯");
                    }
                }
            });
        }
View Code

 

loginController參考

 

/**
     * 獲取驗證碼
     * @param response
     * @param session
     */
    @GetMapping("/getVerifyCode")
    public void generate(HttpServletResponse response, HttpSession session) {
        
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        
        LoginVerifyUtils loginVerifyUtils = LoginVerifyUtils.getInstance();
        String verifyCodeValue =loginVerifyUtils.drawImg(output);
        
        session.setAttribute("verifyCodeValue", verifyCodeValue);
        
        try {
            ServletOutputStream out = response.getOutputStream();
            output.writeTo(out);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    
    //驗證
    @GetMapping("/verifyCode")
    public @ResponseBody AJAXResult verifyCode(@RequestParam("verifyCode") String verifyCode ,HttpSession session) {
        AJAXResult result = new AJAXResult();
        try {
            String verifyCodeValue = (String) session.getAttribute("verifyCodeValue");
            if(verifyCode.trim().toUpperCase().equals(verifyCodeValue)) {
                result.setStateCode("1001");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setStateCode("1003");
        }
        return result;
    }



   @ResponseBody
    @PostMapping("/login")
    public Object login(Admin admin ,HttpServletRequest request) {
        AJAXResult result = new AJAXResult();
        try {
            Wrapper<Admin> wrapper = new EntityWrapper<Admin>();
            wrapper.eq("username", admin.getUsername());
            boolean isName = adminService.selectOne(wrapper) == null ? true: false;
            if(isName) {
                result.setStateCode("1003");//用戶名不存在
            }else {
                Wrapper<Admin> wrapper2 = new EntityWrapper<Admin>();
                wrapper2.eq("username", admin.getUsername());
                wrapper2.eq("password", admin.getPassword());
                Admin loginAdmin = adminService.selectOne(wrapper2);
                if(loginAdmin != null ) {
                    
                    request.getSession().setAttribute("loginAdmin", loginAdmin);
                    
                    LoginLog loginLog = new LoginLog();
                    loginLog.setAdminId(loginAdmin.getId());
                    loginLog.setLoginDate(new Date() );
                    loginLog.setLoginIp(request.getRemoteAddr());
                    loginLogService.insert(loginLog );
                    result.setStateCode( "1001");//登陸成功
                    
                }else {
                    result.setStateCode( "1002");//用戶名或密碼錯誤
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setStateCode( "1004");//伺服器出錯
        }
        return result ;
    }
View Code

 

 ps:主要邏輯就是把隨機生成的驗證碼放到session域,當用戶提交請求時,獲取表單數據然後進行比對<(^-^)>

效果圖

 

 提供的代碼儘量以參考為主,如有疑問,歡迎提出

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 本文內容: Listener Filter 首發日期:2018-07-15 Listener 監聽器Listener負責監聽事件的發生。我們能在事件發生後執行一些自定義的操作,這就是監聽器的意義。 監聽器的本質是介面回調。 分類: 監聽域對象的創建:監聽三個域(request,session,con... ...
  • 關於環境變數的配置,在百度上有很多教程,但對於我來說完成這步操作確實不簡單,所以決定在這裡分享一下配置方法。 1.安裝好jdk/jre。 官網都有安裝文件,仔細一些,就能安裝成功,可以自定義安裝路徑,但是要註意安裝時候不能有中文路徑,否則會報錯。 2.打開此電腦,選擇屬性。 3.選擇高級系統設置。 ...
  • 剛開始接觸這個概念的時候真的是完全不夠理解什麼叫做面向對象,即使到了現在人就是不能夠完全可以說明白。 程式員之路的設計理念分為:面向過程和麵向對象; 面向過程:要想得到一個結果需要一步一步的去設計出來,一步一步的敲代碼去實現這是一個過程。 比如說要比較兩個數的大小有以下程式: int a=3; in ...
  • 一,五大核心組件 1.DispatcherServlet 請求入口 2.HandlerMapping 請求派發,負責請求和控制器建立一一對應的關係 3.Controller 處理器 4.ModelAndView 封裝模型信息和視圖信息 5.ViewResolver 視圖處理器,定位頁面 二,Spri ...
  • JavaDay04總結 1、實現介面VS繼承類 : 1. 實現介面是繼承的補充 2. 實現介面可以在不打破繼承關係的前提下,對某個功能擴展 2、綁定 : 1. 前期綁定:在程式運行前進行綁定,由編譯器和連接程式實現,又叫靜態綁定 2. 後期綁定:在運行時根據對象的類型進行綁定,由方法調用機制實現,又 ...
  • 跟昨天那個自己寫的,沒有按照模板來的一看風格就不相類似,今天模擬賽的時候就是用的我的那個自己YY的代碼,才拿了10分。個人認為關鍵的問題應該在於對於數據的處理太過繁瑣了,所以回來之後,就拿了大佬的程式對照著改。在這裡不得不吐槽一下c++的讀入,cin40分,scanf滿分。還是模板的線段樹比較清晰, ...
  • 在Spring中通過註解@EnableScheduling 來開啟對計劃任務的支持,然後再執行集合任務的方法上註解@Scheduled,聲明這是一個計劃任務。 ...
  • 轉載請註明出處:https://www.cnblogs.com/funnyzpc/p/9190233.html 先來一段詩 ``` 就這樣吧 忍受折磨 然後,躺進醫院 然後,死去 化作一抔土 從此,這世界沒有煩惱 沒有病痛 沒有我 也沒有這個世界 ``` 以上是在半睡半醒中想到的,寫的不好,讀者可直 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...