本文介绍在线生成二维码功能。
思路仿照验证码生成的思路。
代码如下:
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里面的方法,然后以流的方式,生成二维码。