以前只用过jQuery.qrcode生成过二维码,这次使用的是Google的zxing通过Java代码生成二维码并以流的方式输出到前台页面
所需jar包:zxing-3.2.1.jar
代码
前台展示页面
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> 请输入关键字,多个关键字请用逗号隔开 </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> |
后台主要代码
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
|
/** * 生成一个二维码 * @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); //以流的方式输出到前台,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(); } } } } } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://segmentfault.com/a/1190000008523639