標籤:4.0 getmenu new www 簡便 row 思路 hashtable 黑白
本次做訂餐系統中,需要用到在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 exception38 }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 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頁面.
Java產生並列印二維碼