网页端生成二维码的实现方式

来源:互联网 发布:中国移动免流量软件 编辑:程序博客网 时间:2024/06/01 08:06

FTL 文件:

<div class="login-box login-start">    <div class="login-qrcode text-center">      <img id="code2picImg" src="${resRoot}/img/login/qrcode.png" alt="扫描二维码" />      <p>使用XX+APP扫描此二维码,绑定门店</p>    </div>    <div class="login-step">      <span>绑定步骤</span>    </div>    <div class="login-guide">      <img src="${resRoot}/img/login/step.png" alt="">      <ul>        <li>打开XXAPP <br> 进入“工作台”</li>        <li>进入“POS机管理” <br> 点击“添加POS机”</li>        <li>选择绑定的店铺 <br> 扫描此二维码绑定</li>        <li>完成绑定后 <br> POS端即可登录</li>      </ul>    </div>  </div><script type="text/javascript" src="${resRoot}/js/lib/jquery-1.12.4.js"></script>    <script type="text/javascript">    $(function() {         $posCode = $("#posCode").val();         $.ajax({             url : "/generateQrCode.do",             type:"POST",             async: false,             data : {posCode:$posCode},             dataType: "json",             success : function(data) {                                  //二维码初始化                 if (data.CODEPICSTR != undefined && data.CODEPICSTR != "") {                     $("#code2picImg").attr("src", "data:image/jpg;base64,"+data.CODEPICSTR);                 }             },             error : function() {                 console.log("error");             }         });    });    </script> 

服务端:

/**     * 生成二维码     * @param response     * @param posCode     */    @RequestMapping(value = "generateQrCode", method = RequestMethod.POST)    public void generateQrCode(HttpServletResponse response,String posCode) {        Map<String, Object> resultMap = new HashMap<String, Object>();        String codeStr;        try {            codeStr = LoginUtils.getQrCodeImage(posCode);            if(StringUtils.isNotBlank(codeStr)){                resultMap.put("CODEPICSTR", codeStr);            }else{                resultMap.put("CODEPICSTR", "CODEPICERROR");            }        } catch (IOException e) {            logger.error("生成二维码失败,IOException:", e);            resultMap.put("CODEPICSTR", "CODEPICERROR");        }        super.ajaxJson(response, gson.toJson(resultMap));    }

生成二维码工具

package com.suning.sdipospc.util;import goja.QRCode;import goja.QRCodeFormat;import java.awt.image.BufferedImage;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.LineNumberReader;import java.util.regex.Matcher;import java.util.regex.Pattern;import javax.imageio.ImageIO;import javax.servlet.http.HttpServletRequest;import org.apache.commons.lang.StringUtils;import org.apache.commons.net.util.Base64;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.web.context.request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes;/** * 登录工具类 *  * @author 17040365 *  */public class LoginUtils {    /** 日志对象 **/    private static final Logger logger = LoggerFactory            .getLogger(LoginUtils.class);    private static final int QRCODESIZE = 160;    private LoginUtils() {    }    /**     * 生成二维码     *      * @param macAddress     * @return     * @throws IOException     */    public static String getQrCodeImage(String macAddress) throws IOException {        QRCodeFormat codeFormat = QRCodeFormat.NEW();        codeFormat.setSize(QRCODESIZE);        if (StringUtils.isNotBlank(macAddress)) {            BufferedImage bi = QRCode.toQRCode(macAddress, codeFormat);            ByteArrayOutputStream baos = new ByteArrayOutputStream();            ImageIO.write(bi, "jpg", baos);            byte[] bytes = baos.toByteArray();            return Base64.encodeBase64String(bytes).trim();        } else {            return null;        }    }    /**     * 获取远程MAC地址     *      * @return     */    public static String getRemoteMac() {        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder                .getRequestAttributes()).getRequest();        return getRemoteMac(request);    }    /**     * 获取操作系统名称     */    public static String getOsName() {        return System.getProperty("os.name");    }    /**     * 获取远程MAC地址     *      * @param request     * @return     */    public static String getRemoteMac(HttpServletRequest request) {        String ip = getIpAddress(request);        logger.info("============remote ip=======" + ip);        String os = System.getProperty("os.name");        String mac = "";        if (os.startsWith("Windows")) {            mac = getMACAddressWindows(ip);        } else if (os.startsWith("Linux")) {            try {                mac = getMACAddressLinux(ip);            } catch (Exception e) {                logger.error("linux os get mac address fail", e);            }        }        return mac;    }    /**     * 获取IP地址     *      * @param request     * @return     */    public static String getIpAddress(HttpServletRequest request) {        String ip = request.getHeader("X-Forwarded-For");        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {            // 多次反向代理后会有多个ip值,第一个ip才是真实ip            int index = ip.indexOf(',');            if (index != -1) {                return ip.substring(0, index);            } else {                return ip;            }        }        ip = request.getHeader("X-Real-IP");        if (StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {            return ip;        }        return request.getRemoteAddr();    }    /**     * 通过远程IP获取MAC地址(windows)     *      * @param ip     *            远程IP地址     * @return     */    public static String getMACAddressWindows(String ip) {        String str = "";        String macAddress = "";        try {            Process p = Runtime.getRuntime().exec("nbtstat -a " + ip);            InputStreamReader ir = new InputStreamReader(p.getInputStream(),                    "GBK");            LineNumberReader input = new LineNumberReader(ir);            logger.info("nbtstat -a " + ip + "\n mac info:" + str);            while ((str = input.readLine()) != null) {                if (str.indexOf("MAC 地址", 1) > -1) {                    // 客户端使用的是中文版操作系统                    macAddress = str.substring(str.indexOf("MAC 地址") + 9,                            str.length());                    break;                } else if (str.indexOf("MAC Address", 1) > -1) {                    // 客户端使用的是英文版操作系统                    macAddress = str.substring(str.indexOf("MAC Address") + 14,                            str.length());                    break;                }            }        } catch (IOException e) {            logger.error("=========获取远程mac地址异常=======IOException:", e);        }        logger.info("客户端MAC地址:" + macAddress);        return macAddress;    }    /**     * 执行单条指令     *      * @param cmd     *            命令     * @return 执行结果     * @throws Exception     */    public static String command(String cmd) throws Exception {        Process process = Runtime.getRuntime().exec(cmd);        process.waitFor();        InputStream in = process.getInputStream();        StringBuilder result = new StringBuilder();        byte[] data = new byte[256];        while (in.read(data) != -1) {            String encoding = System.getProperty("sun.jnu.encoding");            logger.info("===========system encodeing========="+ encoding);            result.append(new String(data, encoding));        }        return result.toString();    }    /**     * 获取mac地址(linux)     *      * @param ip     * @return     * @throws Exception     */    public static String getMACAddressLinux(String ip) throws Exception {        String result = command("ping " + ip + " -n 2");        if (result.contains("TTL")) {            result = command("arp -a " + ip);        }        String regExp = "([0-9A-Fa-f]{2})([-:][0-9A-Fa-f]{2}){5}";        Pattern pattern = Pattern.compile(regExp);        Matcher matcher = pattern.matcher(result);        StringBuilder mac = new StringBuilder();        while (matcher.find()) {            String temp = matcher.group();            mac.append(temp);        }        return mac.toString();    }}