1. 程式人生 > >JavaWeb實現登入驗證碼

JavaWeb實現登入驗證碼

在登入介面中使用圖片驗證碼, 對於現在的web應用到處可見.

話不多說, 開始寫程式碼了!
首先, 新建一個JSP, 表示登入介面:
login3.jsp檔案:

<%--
  User: menglanyingfei
  Date: 2018/1/12
  Time: 16:16
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head> <title>登入介面</title> </head> <body> <% // 獲取瀏覽器傳送過來的cookie, 獲取使用者資訊 Cookie[] cookies = request.getCookies(); String username = ""; if (cookies != null) { for (Cookie cookie : cookies) { if ("username".equals(cookie.getName())) { username = cookie.getValue(); } } } %>
<font color="red">${requestScope.message}</font> <form action="/day_1_12/LoginServlet3" method="post"> 使用者名稱:<input type="text" name="username" value="<%= username%>"><font color="red">${requestScope.error}</font> <br> 密碼:<input type="password"
name="password">
<br> 驗證碼:<input type="text" name="image"> <img src="/day_1_12/VerifyCodeServlet"> <input type="button" value="看不清? 換一張." id="btn"><font color="red">${requestScope.imageMess}</font> <br> <input type="submit" value="登入"> </form> <script type="text/javascript"> document.getElementById("btn").onclick = function () { // 獲取img元素 // 為了讓瀏覽器傳送請求到servlet, 所以一定要改變src document.getElementsByTagName("img")[0].src = "/day_1_12/VerifyCodeServlet?time=" + new Date().getTime(); }; </script> </body> </html>

介面就是這樣, 當然, 你肯定現在出來不了這個效果! 沒事, 接著往下看吧!
登入介面.png

然後, 新建一個Servlet:
VerifyCodeServlet.java檔案, 因為這裡配置了@WebServlet註解, 所以無需在web.xml中配置!

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 用來生成圖片驗證碼
 * Created by menglanyingfei on 2018/1/12.
 */
@WebServlet(name = "VerifyCodeServlet", value = "/VerifyCodeServlet")
public class VerifyCodeServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //建立物件
        VerifyCode vc = new VerifyCode();
        //獲取圖片物件
        BufferedImage bi = vc.getImage();
        //獲得圖片的文字內容
        String text = vc.getText();
        // 將系統生成的文字內容儲存到session中
        request.getSession().setAttribute("text", text);
        //向瀏覽器輸出圖片
        vc.output(bi, response.getOutputStream());

    }
}

在同一包下, 新建一個Java檔案VerifyCode.java(具體的程式碼意思, 可以看註釋, 已經寫得非常清楚了!):

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;

public class VerifyCode {
    private int w = 70;
    private int h = 35;
    private Random r = new Random();
    // {"宋體", "華文楷體", "黑體", "華文新魏", "華文隸書", "微軟雅黑", "楷體_GB2312"}
    private String[] fontNames  = {"宋體", "華文楷體", "黑體", "微軟雅黑", "楷體_GB2312"};
    // 可選字元
    private String codes  = "0123456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
    // 背景色
    private Color bgColor  = new Color(255, 255, 255);
    // 驗證碼上的文字
    private String text ;

    // 生成隨機的顏色
    private Color randomColor () {
        int red = r.nextInt(150);
        int green = r.nextInt(150);
        int blue = r.nextInt(150);
        return new Color(red, green, blue);
    }

    // 生成隨機的字型
    private Font randomFont () {
        int index = r.nextInt(fontNames.length);
        String fontName = fontNames[index];//生成隨機的字型名稱
        int style = r.nextInt(4);//生成隨機的樣式, 0(無樣式), 1(粗體), 2(斜體), 3(粗體+斜體)
        int size = r.nextInt(5) + 24; //生成隨機字號, 24 ~ 28
        return new Font(fontName, style, size);
    }

    // 畫干擾線
    private void drawLine (BufferedImage image) {
        int num  = 3;//一共畫3條
        Graphics2D g2 = (Graphics2D)image.getGraphics();
        for(int i = 0; i < num; i++) {//生成兩個點的座標,即4個值
            int x1 = r.nextInt(w);
            int y1 = r.nextInt(h);
            int x2 = r.nextInt(w);
            int y2 = r.nextInt(h); 
            g2.setStroke(new BasicStroke(1.5F)); 
            g2.setColor(Color.BLUE); //干擾線是藍色
            g2.drawLine(x1, y1, x2, y2);//畫線
        }
    }

    // 隨機生成一個字元
    private char randomChar () {
        int index = r.nextInt(codes.length());
        return codes.charAt(index);
    }

    // 建立BufferedImage
    private BufferedImage createImage () {
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); 
        Graphics2D g2 = (Graphics2D)image.getGraphics(); 
        g2.setColor(this.bgColor);
        g2.fillRect(0, 0, w, h);
        return image;
    }

    // 呼叫這個方法得到驗證碼
    public BufferedImage getImage () {
        BufferedImage image = createImage();//建立圖片緩衝區 
        Graphics2D g2 = (Graphics2D)image.getGraphics();//得到繪製環境
        StringBuilder sb = new StringBuilder();//用來裝載生成的驗證碼文字
        // 向圖片中畫4個字元
        for(int i = 0; i < 4; i++)  {//迴圈四次,每次生成一個字元
            String s = randomChar() + "";//隨機生成一個字母 
            sb.append(s); //把字母新增到sb中
            float x = i * 1.0F * w / 4; //設定當前字元的x軸座標
            g2.setFont(randomFont()); //設定隨機字型
            g2.setColor(randomColor()); //設定隨機顏色
            g2.drawString(s, x, h-5); //畫圖
        }
        this.text = sb.toString(); //把生成的字串賦給了this.text
        drawLine(image); //新增干擾線
        return image;       
    }

    // 返回驗證碼圖片上的文字
    public String getText () {
        return text;
    }

    // 儲存圖片到指定的輸出流
    public static void output (BufferedImage image, OutputStream out) 
                throws IOException {
        ImageIO.write(image, "JPEG", out);
    }
}

處理登入邏輯的Servlet(LoginServlet3.java):

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by menglanyingfei on 2018/1/12.
 */
@WebServlet(name = "LoginServlet3", value = "/LoginServlet3")
public class LoginServlet3 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 編碼
        request.setCharacterEncoding("utf-8");
        // 獲取請求引數
        /*
            拿到頁面傳過來的手動輸入的驗證碼, 該驗證碼要和生成圖片上的
            文字驗證碼比較, 如果相同, 驗證碼輸入成功!
         */
        String imageText = request.getParameter("image");
        // 圖片的驗證碼
        String text = (String) request.getSession().getAttribute("text");

        if (!text.equalsIgnoreCase(imageText)) {
            request.setAttribute("imageMess", "驗證碼輸入錯誤!");
            request.getRequestDispatcher("/jsp/login3.jsp").forward(request, response);
        }
        // 獲取使用者名稱和密碼
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if ("haha".equals(username) && "123".equals(password)) {
            // 將使用者資訊儲存到session中
            request.getSession().setAttribute("username", username);

            // 使用cookie實現回寫使用者名稱
            Cookie cookie = new Cookie("username", username);
            cookie.setMaxAge(60 * 60);
            // 通過響應頭髮送cookie
            response.addCookie(cookie);
            // 重定向登入成功介面
            response.sendRedirect(request.getContextPath() + "/jsp/success2.jsp");
        } else {
            request.setAttribute("error", "使用者名稱或密碼錯誤!");
            request.getRequestDispatcher("/jsp/login3.jsp").forward(request, response);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }
}

登入成功後的介面:(success2.jsp)

<%--
  User: menglanyingfei
  Date: 2018/1/12
  Time: 16:44
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <title>成功登入</title>
</head>
<body>
<%
    // 獲取使用者資訊
    String username = (String) session.getAttribute("username");

    if (username == null) {
        // 儲存錯誤資訊到request中, 然後轉發到login3.jsp中, 提醒登入
        request.setAttribute("message", "請登入!");

        // 轉發到登入頁面
        request.getRequestDispatcher("/jsp/login3.jsp").forward(request, response);
    }
%>
<h2>歡迎登入:${sessionScope.username}!!!</h2>
</body>
</html>

最後, 演示登入:
因為, 使用者名稱haha和密碼123已經寫死在程式碼裡了!
登入.png
成功.png

完整程式碼地址