在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); //设定图像颜色:BLACK gs.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; @Override protected 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;80px" src="code.jspx" />
6.页面中生成的二维码