以前只用過(guò)jQuery.qrcode生成過(guò)二維碼,這次使用的是Google的zxing通過(guò)Java代碼生成二維碼并以流的方式輸出到前臺(tái)頁(yè)面
所需jar包:zxing-3.2.1.jar
代碼
前臺(tái)展示頁(yè)面
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
<%@ page language= "java" import= "java.util.*" pageEncoding= "UTF-8" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+ "://" +request.getServerName()+ ":" +request.getServerPort()+path+ "/" ; %> <!DOCTYPE html> <html> <head> <title>二維碼</title> <meta http-equiv= "Content-Type" content= "text/html; charset=UTF-8" > <script src= "http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js" ></script> <style> body{text-align:center;} </style> </head> <body> 請(qǐng)輸入關(guān)鍵字,多個(gè)關(guān)鍵字請(qǐng)用逗號(hào)隔開(kāi) </br> </br> <textarea id= "ids" cols= "30" rows= "10" > </textarea> </br> <button onclick= "submit1()" value= "提交" >提交</button> </br> </br> </br> <div id= "img" > </div> <script> function submit1() { var reg = new RegExp( "," , "g" ); //替換所有"," var ids = $( "#ids" ).val().replace(reg, "," ).split( "," ); var html = "<table align=\"center\">" ; for ( var i = 0; i<ids.length; i++){ html += "<tr><td>" + ids[i] + "</td></tr>" html += "<tr><td><img src=\"<%=basePath%>qrCode/generateOneqrCode/?id=" + ids[i] + "\" /></td></tr>" ; } html += "</table>" ; $( "#img" ).html(html); } </script> </body> </html> |
后臺(tái)主要代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
/** * 生成一個(gè)二維碼 * @param resp * @param id */ @Override public void generateOneqrCode(HttpServletResponse resp, String id) { if (TextUtil.isNotEmpty(id)) { ServletOutputStream stream = null ; try { int width = 200 ; //圖片的寬度 int height = 200 ; //圖片的高度 stream = resp.getOutputStream(); QRCodeWriter writer = new QRCodeWriter(); BitMatrix m = writer.encode(id, BarcodeFormat.QR_CODE, height, width); //以流的方式輸出到前臺(tái),action中return null就可以 MatrixToImageWriter.writeToStream(m, "png" , stream); } catch (IOException e) { e.printStackTrace(); } catch (WriterException e1) { e1.printStackTrace(); } finally { if (stream != null ) { try { stream.flush(); stream.close(); } catch (IOException e) { e.printStackTrace(); } } } } } |
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://segmentfault.com/a/1190000008523639