使用zxing生成二维码,使用的jar包为 zxing3.2.1.jar
1、servlet代码
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
/**
* Servlet implementation class QRcode
*/
@WebServlet("/QRcode")
public class QRcode extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String KEY = "keycode";
private static final String SIZE = "msize";
private static final String IMAGETYPE = "JPEG";
/**
* @see HttpServlet#HttpServlet()
*/
public QRcode() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String keycode = request.getParameter(KEY);
if (keycode != null && !"".equals(keycode)) {
ServletOutputStream stream = null;
try {
int size = 300;
String msize = request.getParameter(SIZE);
if (msize != null && !"".equals(msize.trim())) {
try {
size = Integer.valueOf(msize);
} catch(NumberFormatException e) {
}
}
stream = response.getOutputStream();
QRCodeWriter writer = new QRCodeWriter();
BitMatrix m = writer.encode(keycode, BarcodeFormat.QR_CODE, size, size);
MatrixToImageWriter.writeToStream(m, IMAGETYPE, stream);
} catch (WriterException e) {
e.printStackTrace();
} finally {
if(stream != null) {
stream.flush();
stream.close();
}
}
}
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
2、web.xml配置
<servlet>
<servlet-name>qrCode</servlet-name>
<servlet-class>servlet.QRcode</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>qrCode</servlet-name>
<url-pattern>/qrCode</url-pattern>
</servlet-mapping>
3、jsp页面
<img alt="二维码" src="${pageContext.request.contextPath}/qrCode?keycode=www.bing.com"></img>
4、运行测试