在java中產生的二維碼不存到磁碟裡要直接輸出到頁面上,這就需要把產生的二維碼直接以流的形式輸出到頁面上,我用的是myeclipse 和 tomcat
它的原理是:在載入頁面時,根據img的src(code.jspx)找到對應的servlet(CodeServlet),在servlet中編輯二維碼中的內容,調用產生二維碼的類EncoderHandler中的encoderQRcoder方法
1.首先要匯入jar包(將jar包放到lib目錄下)
匯入jar包的名稱為:Qrcode_swetake
下載jar包的串連http://download.csdn.net/detail/huakaihualuo1223/4527504
2.在java中產生二維碼並以流的形式輸出
package com.kaishengit.util;import java.awt.Color;import java.awt.Graphics2D;import java.awt.image.BufferedImage;import javax.imageio.ImageIO;import javax.servlet.http.HttpServletResponse;import com.swetake.util.Qrcode;public class EncoderHandler {public void encoderQRCoder(String content, HttpServletResponse response) {try {Qrcode handler = new Qrcode();handler.setQrcodeErrorCorrect('M');handler.setQrcodeEncodeMode('B');handler.setQrcodeVersion(7);System.out.println(content);byte[] contentBytes = content.getBytes("UTF-8");BufferedImage bufImg = new BufferedImage(80, 80, BufferedImage.TYPE_INT_RGB);Graphics2D gs = bufImg.createGraphics();gs.setBackground(Color.WHITE);gs.clearRect(0, 0, 140, 140);//設定映像顏色:BLACKgs.setColor(Color.BLACK);//設定位移量 不設定肯能導致解析出錯int pixoff = 2;//輸出內容:二維碼if(contentBytes.length > 0 && contentBytes.length < 124) {boolean[][] codeOut = handler.calQrcode(contentBytes);for(int i = 0; i < codeOut.length; i++) {for(int j = 0; j < codeOut.length; j++) {if(codeOut[j][i]) {gs.fillRect(j * 3 + pixoff, i * 3 + pixoff,3, 3);}}}} else {System.err.println("QRCode content bytes length = " + contentBytes.length + " not in [ 0,120 ]. ");}gs.dispose();bufImg.flush();//產生二維碼QRCode圖片ImageIO.write(bufImg, "jpg", response.getOutputStream());} catch (Exception e) {e.printStackTrace();}}}
3.建立一個servlet
package com.kaishengit.web;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.kaishengit.util.EncoderHandler;public class CodeServlet extends HttpServlet {private static final long serialVersionUID = 1L;@Overrideprotected void service(HttpServletRequest requset, HttpServletResponse response)throws ServletException, IOException {String content = "姓名:maysnow 電話:123687495";EncoderHandler encoder = new EncoderHandler();encoder.encoderQRCoder(content, response);}}
4在web.xml中的配置
<servlet> <servlet-name>CodeService</servlet-name> <servlet-class>com.kaishengit.web.CodeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CodeService</servlet-name> <url-pattern>/code.jspx</url-pattern> </servlet-mapping>
5.jsp中的img(其中img的src為對應的CodeServlet的url)
<img style="height:80px;width:80px" src="code.jspx" />
6.頁面中產生的二維碼