本次做訂餐系統中,需要用到在Java生成二維碼,並在jsp頁面打印並輸出,其中在action中生成二維碼.
關鍵代碼如下
1 public void reWeiMa() throws Exception{ 2 //設置頁面不緩存 3 HttpServletResponse response = ServletActionContext.getResponse(); 4 HttpServletRequest quest = ServletActionContext.getRequest(); 5 Domain domain=domainService.getIp(); 6 if(domain!=null){ 7 String IP =domain.getIp(); 8 response.setHeader("Pragma","No-cache"); 9 response.setHeader("Cache-Control","no-cache"); 10 response.setDateHeader("Expires", 0); 11 12 BufferedImage image=null; 13 ServletOutputStream stream = null; 14 //二維碼的圖片格式 15 String format = "gif"; 16 String path= quest.getScheme() + "://"+IP+ ":" + quest.getServerPort()+ quest.getContextPath() + "/"; 17 String content=path+"OrderDetail_getMenuMaterial?menuId="+menuId; 18 int width2 = 200; 19 int height2 = 200; 20 21 Hashtable hints = new Hashtable(); 22 //內容所使用編碼 23 hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); 24 25 try{ 26 BitMatrix bitMatrix = new MultiFormatWriter().encode(content,BarcodeFormat.QR_CODE, width2, height2, hints); 27 int width = bitMatrix.getWidth(); 28 int height = bitMatrix.getHeight(); 29 image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 30 for (int x = 0; x < width; x++) { 31 for (int y = 0; y < height; y++) { 32 image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); //二維碼圖片為黑白兩色 33 } 34 } 35 //ImageIO.write(image,"gif",response.getOutputStream()); 36 }catch (Exception e) { 37 // TODO: handle exception 38 } 39 //只有用這種解碼方式才不出現亂碼 40 String s="attachment;filename="+new String("No"+menuId+".gif"); 41 response.addHeader("Content-Disposition",s); 42 OutputStream os=new BufferedOutputStream(response.getOutputStream()); 43 response.setContentType("image/gif"); 44 ImageIO.write(image,format,os); 45 os.flush(); 46 os.close(); 47 }else{ 48 String messige="未添加域名,暫無法打印二維碼"; 49 request.put("messige", messige); 50 } 51 }
jsp頁面代調用生成二維碼方法后,返回到打印二維碼jsp中,代碼如下
1 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 2 pageEncoding="ISO-8859-1"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 7 <title>Insert title here</title> 8 </head> 9 <body> 10 <div style="text-align:center;"> 11 <img alt="" src="${rootPath}/OrderDetail_reWeiMa?menuId=${menuId}"> 12 </div> 13 14 <script type="text/javascript"> 15 window.onload = function(){ 16 window.print() 17 window.close()//打印后返回到原界面 18 } 19 20 </script> 21 </body> 22 </html>
在這里的思路是在action生成的的二維碼放入src標簽中,直接打印整個jsp,在這個過程中,遇到了一個問題,原本調用Java內部print方法來打印二維碼,但在這個過程中遇到系統無法找到指定路徑,(二維碼生成在服務器上,瀏覽器調用服務器內容),最后使用簡便方法,直接打印整個jsp頁面.