一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Java使用Google Zxing生成二维码的例子

时间:2022-06-29 01:34:50 编辑:袖梨 来源:一聚教程网

以前只用过jQuery.qrcode生成过二维码,这次使用的是Google的zxing通过Java代码生成二维码并以流的方式输出到前台页面

所需jar包:zxing-3.2.1.jar

代码

前台展示页面

代码如下 复制代码

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>

二维码

body{text-align:center;}

请输入关键字,多个关键字请用逗号隔开

functionsubmit1() {

varreg =newRegExp(",","g");//替换所有","

varids = $("#ids").val().replace(reg,",").split(",");

varhtml ="

";

for(vari = 0; i

html +="

"

html +="

";

}

html +="

"+ ids[i] +"
qrCode/generateOneqrCode/?id="+ ids[i] +"" />
";

$("#img").html(html);

}

后台主要代码

代码如下 复制代码

/**

* 生成一个二维码

* @param resp

* @param id

*/

@Override

publicvoidgenerateOneqrCode(HttpServletResponse resp, String id) {

if(TextUtil.isNotEmpty(id)) {

ServletOutputStream stream =null;

try{

intwidth =200;//图片的宽度

intheight =200;//图片的高度

stream = resp.getOutputStream();

QRCodeWriter writer =newQRCodeWriter();

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();

}

}

}

}

}

热门栏目