在jsp頁面產生二維碼,jsp頁面
本文介紹線上產生二維碼功能。
思路仿照驗證碼產生的思路。
代碼如下:
package com.sys.productNew.action;import java.awt.image.BufferedImage;import java.io.IOException;import java.io.OutputStream;import javax.imageio.ImageIO;import javax.servlet.http.HttpServletResponse;import org.apache.struts2.ServletActionContext;import com.huchi.util.qrutils.PictureUtils;import com.opensymphony.xwork2.Action;import com.opensymphony.xwork2.ActionSupport;public class ProductNewAction extends ActionSupport {// 產品編號private String productId;// 跳到二維碼頁面public String prevQRPicture() throws IOException {return Action.SUCCESS;}//產生預覽二維碼public void QRPicture() {HttpServletResponse response=ServletActionContext.getResponse();response.setDateHeader("Expires", 0);response.setHeader("Cache-Control", "no-cache");response.setHeader("Pragma", "No-cache");response.setContentType("image/jpeg");// 產生二維碼String url = "http://xx/yy/zz.action?productId=";BufferedImage image = PictureUtils.generateQRCode(url + productId);OutputStream os = null;try {os = response.getOutputStream();ImageIO.write(image, "JPEG", os);} catch (IOException e) {e.printStackTrace();} finally { if (os != null) {try {os.close();} catch (IOException e) {e.printStackTrace();}}}}public String getProductId() {return productId;}public void setProductId(String productId) {this.productId = productId;}}
HTML :
<img alt="呼哧旅行" id="authCodeImage" src="/end/app/productNew/QRPicture.shtml?productId=${productId }"/>
該功能能夠將二維碼,以流的方式,寫在JSP頁面上。需要注意的是,通過<img>的src功能,訪問action裡面的方法,然後以流的方式,產生二維碼。