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