利用google的开源包zxing生成二维码
第一步:maven项目的zxing依赖
<!-- google zxing 生成二维码 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.2.0</version>
</dependency>
第二步:jsp页面上写上调用生成二维码的controller图片标签
<%@page import="sun.tools.tree.ThisExpression"%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<h1>微信扫码支付,请扫下面二维码</h1>
<img class="q_code" src="<%=this.getServletContext().getContextPath() %>/services/wapwxdemo/getErWeiCode" />
</body>
</html>
第三步:生成二维码的controller方法
/**
* 生成二维码,返回到页面上
* @param response
*/
@RequestMapping(value="/getErWeiCode",method={RequestMethod.POST,RequestMethod.GET} )
public void getErWeiCode(HttpServletResponse response){
String url="www.baidu.com";
if(url!=null&&!"".equals(url)){
ServletOutputStream stream=null;
try {
int width=200;
int height=200;
stream=response.getOutputStream();
QRCodeWriter writer=new QRCodeWriter();
BitMatrix m=writer.encode(url, BarcodeFormat.QR_CODE, height,width);
MatrixToImageWriter.writeToStream(m, "png", stream);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
if(stream!=null){
try {
stream.flush();
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} }
}
}
}
第四步:效果展示