【微信開發】SpringMVC將url生成二維碼圖片直接展示在頁面上
阿新 • • 發佈:2019-02-01
利用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 }
第四步:效果展示
如果用HTML 直接將<img>的src屬性設定為url
歡迎關注公眾號: