Java使用Google Zxing生成二维码的例子
以前只用过jQuery.qrcode生成过二维码,这次使用的是Google的zxing通过Java代码生成二维码并以流的方式输出到前台页面
所需jar包:zxing-3.2.1.jar
代码
前台展示页面
<%@pagelanguage="java"import="java.util.*"pageEncoding="UTF-8"%>
<%
Stringpath=request.getContextPath();
StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPEhtml>
<html>
<head>
<title>二维码</title>
<metahttp-equiv="Content-Type"content="text/html;charset=UTF-8">
<scriptsrc="http://apps.bdimg.com/libs/jquery/1.9.1/jquery.min.js"></script>
<style>
body{text-align:center;}
</style>
</head>
<body>
请输入关键字,多个关键字请用逗号隔开
</br>
</br>
<textareaid="ids"cols="30"rows="10">
</textarea>
</br>
<buttononclick="submit1()"value="提交">提交</button>
</br>
</br>
</br>
<divid="img">
</div>
<script>
functionsubmit1(){
varreg=newRegExp(",","g");//替换所有","
varids=$("#ids").val().replace(reg,",").split(",");
varhtml="<tablealign=\"center\">";
for(vari=0;i<ids.length;i++){
html+="<tr><td>"+ids[i]+"</td></tr>"
html+="<tr><td><imgsrc=\"<%=basePath%>qrCode/generateOneqrCode/?id="+ids[i]+"\"/></td></tr>";
}
html+="</table>";
$("#img").html(html);
}
</script>
</body>
</html>
后台主要代码
/**
*生成一个二维码
*@paramresp
*@paramid
*/
@Override
publicvoidgenerateOneqrCode(HttpServletResponseresp,Stringid){
if(TextUtil.isNotEmpty(id)){
ServletOutputStreamstream=null;
try{
intwidth=200;//图片的宽度
intheight=200;//图片的高度
stream=resp.getOutputStream();
QRCodeWriterwriter=newQRCodeWriter();
BitMatrixm=writer.encode(id,BarcodeFormat.QR_CODE,height,width);
//以流的方式输出到前台,action中returnnull就可以
MatrixToImageWriter.writeToStream(m,"png",stream);
}catch(IOExceptione){
e.printStackTrace();
}catch(WriterExceptione1){
e1.printStackTrace();
}finally{
if(stream!=null){
try{
stream.flush();
stream.close();
}catch(IOExceptione){
e.printStackTrace();
}
}
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。