java generate QR code scan web page automatic login function

Looking for a lot of information, seven, eight, eight have tried again, and finally wrote out this function.

A rookie. This article is only for notes.

A simple generation of QR code, through the web page to confirm the login, to achieve the QR code page to jump to the main page.

There are three servlet s:

CodeServlet.java does two things

A: generate a random uuid, which is a unique identifier throughout the whole process

b: generate QR code picture, QR code information: http://xx.xx.xx.xx:8080/xxxx/login.jsp?uuid= xxxx

LongConnectionCheckServlet.java 

Perform the long connection polling operation. The parameter is uuid. Check whether there is such uuid in loginMap. If there is, stop polling. remove the uuid in loginMap

PhoneLoginServlet.java does two things

a: check the login to see if there is this uuid

b: after successful login, insert the login information into loginMap, and uuid is key

--------Servlet needs to configure web.xml--------

UserLoginInfoVO.java

User login information stores user name and password (others can be added, I only write simple ones)

LoginUser.java

Save user login information with HashMap

TwoDimensionCode.java

The most critical class to generate QR code and implement QRCodeImage requires QRCode.jar package

QRCode.jar download address: http://vdisk.weibo.com/s/A25JOYrYFK9xO

 

UserLoginInfoVO.java

public class UserLoginInfoVO {
    private String userName;
    private String userPass;

    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getUserPass() {
        return userPass;
    }
    public void setUserPass(String userPass) {
        this.userPass = userPass;
    }
}

 

LoginUser.java

import java.util.HashMap;

public class LoginUser { private static HashMap<String, UserLoginInfoVO> loginMap = new HashMap<String, UserLoginInfoVO>(); private static UserLoginInfoVO userLoginInfoVO; public static UserLoginInfoVO getVO() { if (userLoginInfoVO == null) { userLoginInfoVO = new UserLoginInfoVO(); } return userLoginInfoVO; } public static HashMap<String, UserLoginInfoVO> getLoginMap() { return loginMap; } }

 

TwoDimensionCode.java

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import com.swetake.util.Qrcode;
import jp.sourceforge.qrcode.QRCodeDecoder;
import jp.sourceforge.qrcode.exception.DecodingFailedException;

public class TwoDimensionCode {
    /**
     * Generate QR code image
     * 
     * @param content
     *            Storage content
     * @param imgPath
     *            Picture path
     * @param imgType
     *            Picture type
     * @param output
     *            Output stream
     * @param size
     *            QR code size
     */
    public void encoderQRCode(String content, String imgPath) {
        this.encoderQRCode(content, imgPath, "png", 7);
    }

    public void encoderQRCode(String content, OutputStream output) {
        this.encoderQRCode(content, output, "png", 7);
    }

    public void encoderQRCode(String content, String imgPath, String imgType) {
        this.encoderQRCode(content, imgPath, imgType, 7);
    }

    public void encoderQRCode(String content, OutputStream output, String imgType) {
        this.encoderQRCode(content, output, imgType, 7);
    }

    public void encoderQRCode(String content, String imgPath, String imgType, int size) {
        try {
            BufferedImage bufImg = this.qRCodeCommon(content, imgType, size);

            File imgFile = new File(imgPath);
            if (!imgFile.exists()) {
                imgFile.mkdirs();
            }
            // Generate QR code QRCode picture
            ImageIO.write(bufImg, imgType, imgFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void encoderQRCode(String content, OutputStream output, String imgType, int size) {
        try {
            BufferedImage bufImg = this.qRCodeCommon(content, imgType, size);
            // Generate QR code QRCode picture
            ImageIO.write(bufImg, imgType, output);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * A common method of generating QR code pictures
     * 
     * @return BufferedImage
     */
    private BufferedImage qRCodeCommon(String content, String imgType, int size) {
        BufferedImage bufImg = null;
        try {
            Qrcode qrcode = new Qrcode();
            // Set the error rate of QR code, optional L(7%),M(15%),Q(25%),H(30%),The higher the error rate, the less information can be stored, but the less the requirement for the definition of QR code is
            qrcode.setQrcodeErrorCorrect('M');
            qrcode.setQrcodeEncodeMode('B');
            // Set and set QR code size, value range 1-40,The larger the value, the larger the size, the larger the information that can be stored
            qrcode.setQrcodeVersion(size);
            // Get byte array of content, set encoding format
            byte[] contentBytes = content.getBytes("utf-8");
            // Picture size
            int imgSize = 67 + 12 * (size - 1);
            // BufferedImage.TYPE_INT_RGB Represents an image with 8 bits of integer pixels RGB colour
            bufImg = new BufferedImage(imgSize, imgSize, BufferedImage.TYPE_INT_RGB);

            Graphics2D gs = bufImg.createGraphics();
            // Set background color
            gs.setBackground(Color.WHITE);
            // Draw rectangle
            gs.clearRect(0, 0, imgSize, imgSize);

            // Set image color BLACK
            gs.setColor(Color.BLACK);
            // Set offset, not setting may cause parsing error
            int pixoff = 2;
            // Output content> QR code
            if (contentBytes.length > 0 && contentBytes.length < 800) {
                // calQrcode()Let the string generate the QR code.
                boolean[][] codeOut = qrcode.calQrcode(contentBytes);
                for (int i = 0; i < codeOut.length; i++) {
                    for (int j = 0; j < codeOut.length; j++) {
                        if (codeOut[j][i]) {
                            gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
                        }
                    }
                }
            } else {
                throw new Exception("QRCode content bytes length = " + contentBytes.length + " not in [0, 800].");
            }
            gs.dispose();
            bufImg.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bufImg;
    }
}

 

CodeServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dsjstudio.loanfront.useras.utils.TwoDimensionCode;

public class CodeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        // Generating uniqueness ID
        int uuid = (int) (Math.random() * 100000);
        // QR code content
        String content = "http://localhost:8080/xxxx/index.jsp?uuid=" + uuid;
        // Generate QR code
        String imgName = "image_" + uuid + ".png";
        String imgPath = "D:/images/" + imgName;

        TwoDimensionCode handler = new TwoDimensionCode();
        handler.encoderQRCode(content, imgPath, "png");

        System.out.println(content);
        // Generated image access address
        String qrCodeImg = "http://localhost:8080/images/" + imgName;
        String jsonStr = "{\"uuid\":" + uuid + ",\"qrCodeImg\":\"" + qrCodeImg + "\"}";
        out.print(jsonStr);
        out.flush();
        out.close();

    }
}

 

LongConnectionCheckServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dsjstudio.loanfront.useras.controller.user.controller.LoginUser;
import com.dsjstudio.loanfront.useras.controller.user.vo.UserLoginInfoVO;

public class LongConnectionCheckServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

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

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

        String uuid = request.getParameter("uuid");
        String jsonStr = "";
        System.out.println("in");
        System.out.println("uuid:" + uuid);
        long inTime = new Date().getTime();
        Boolean bool = true;
        while (bool) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // Detection login
            UserLoginInfoVO userVo = LoginUser.getLoginMap().get(uuid);
            System.out.println("userVo:" + userVo);
            if (userVo != null) {
                bool = false;
                jsonStr = "{\"uname\":\"" + userVo.getUserName() + "\"}";
                LoginUser.getLoginMap().remove(uuid);
            } else {
                if (new Date().getTime() - inTime > 5000) {
                    bool = false;
                }
            }
        }
        System.out.println("login ok : " + jsonStr);
        PrintWriter out = response.getWriter();
        out.print(jsonStr);
        out.flush();
        out.close();
    }

}

 

PhoneLoginServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dsjstudio.loanfront.useras.controller.user.controller.LoginUser;
import com.dsjstudio.loanfront.useras.controller.user.vo.UserLoginInfoVO;

public class PhoneLoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

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

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String uuid = request.getParameter("uuid");
        String uname = request.getParameter("uname");
        String upwd = request.getParameter("upwd");
        System.out.println(uuid);
        System.out.println(uname);
        System.out.println(upwd);
        // TODO Verify login
        boolean bool = true;
        if (bool) {
            // Save login information map
            UserLoginInfoVO userVo = LoginUser.getLoginMap().get(uuid);
            if (userVo == null) {
                userVo = new UserLoginInfoVO();
                userVo.setUserName(uname);
                userVo.setUserPass(upwd);
                LoginUser.getLoginMap().put(uuid, userVo);
            }
        }
        PrintWriter out = response.getWriter();
        out.print(bool);
        out.flush();
        out.close();
    }

}

 

Two jsp pages:

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        var uuid;
        //alert("1");
        $.get("/dsjstudio-loan-user-as/CodeServlet", function(data, status) {
            var obj = eval("(" + data + ")");
            //alert("2");
            //storage UUID
            uuid = obj.uuid;
            //Show QR code
            $("#QrCodeImg").attr("src", obj.qrCodeImg);
           // alert(obj.qrCodeImg);
            //Start verifying login
            validateLogin();
        });
        function validateLogin(){
            $.get("/dsjstudio-loan-user-as/LongConnectionCheckServlet?uuid=" + uuid , function(data, status) {
                if(data == ""){
                    validateLogin();
                }else{
                    var obj = eval("(" + data + ")");
                    alert("Welcome home:" + obj.uname);
                    window.location.href='http://www.baidu.com';
                }
            });
        }
    });
</script>
</head>
<body>
<h1>Brother dare not sweep it!</h1>
    <div id="divCon">
        <img src="" id="QrCodeImg" />
    </div>
</body>
</html>

 

login.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Let's make sure, young man</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
    //Sign in
    function login()
        $.post("/dsjstudio-loan-user-as/PhoneLoginServlet", {
            uuid : $.getUrlParam('uuid'),
            uname:$("#login_name").val(),
            upwd:$("#login_psw").val()
        }, function(data, status) {
            if(data == ""){
                alert("Login failed");
            }else{
                alert("Login successfully");
            }
        });
    }
    //Get page parameters
    (function($){
            $.getUrlParam = function(name){
                //This rule is looking for&+url Parameter name=value+&
                var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
                //Here is the start of matching. The return correspondence is found url Value, no return found null. 
                var r = window.location.search.substr(1).match(reg);
                if (r!=null) return unescape(r[2]); return null;
            }
        })(jQuery);
</script>
</head>
<body>
    <div>
        <p>
            <span>Name:</span>
            <input type="text" id="login_name" value="lingzi">
        </p>
        <p>
            <span>Password:</span>
            <input type="password" id="login_psw" value="xxxxxxxxx">
        </p>
        <div>
            <a href="javascript:login()">Sign in</a>
        </div>
    </div>
</body>
</html>

 

 

Because it is connected to the local tomcat, it is operated directly on the computer. The two-dimensional code is generated. A uuid is printed on the Console, copied and pasted to the website

Implementation effect diagram:

 

 

uuid printed on Console 62951

 

 

Click to log in

 

 

Return to the index.jsp page to view, succeeded ~ click OK to jump to the page~

 

 

web.xml configuration

 

  <servlet>
        <description></description>
        <display-name>Long connection check login status</display-name>
        <servlet-name>LongConnectionCheckServlet</servlet-name>
        <servlet-class>com.dsjstudio.loanfront.useras.controller.user.servlet.LongConnectionCheckServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LongConnectionCheckServlet</servlet-name>
        <url-pattern>/LongConnectionCheckServlet</url-pattern>
    </servlet-mapping>

    <servlet>
        <description>Get QR code pictures and uuid</description>
        <display-name>CodeServlet</display-name>
        <servlet-name>CodeServlet</servlet-name>
        <servlet-class>com.dsjstudio.loanfront.useras.controller.user.servlet.CodeServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>CodeServlet</servlet-name>
        <url-pattern>/CodeServlet</url-pattern>
    </servlet-mapping>

    <servlet>
        <description>Login after scanning QR code</description>
        <display-name>PhoneLoginServlet</display-name>
        <servlet-name>PhoneLoginServlet</servlet-name>
        <servlet-class>com.dsjstudio.loanfront.useras.controller.user.servlet.PhoneLoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>PhoneLoginServlet</servlet-name>
        <url-pattern>/PhoneLoginServlet</url-pattern>
    </servlet-mapping>

Tags: Java QRCode JSP Javascript

Posted on Sun, 29 Mar 2020 12:37:16 -0400 by welshmike