struts2中生成二维码

最近写项目用到了二维码,用于用户扫码临时登录,开始时是生成二维码,保存到项目中的文件夹,在提供一个下载功能,后来感觉这样有点麻烦,如果直接生成后发送到客户端的页面多好,后来做到了这样,下面是我的实现代码

 

public void erWeiMa() throws Exception {
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest quest = ServletActionContext.getRequest();
		Domain domain = domainService.getIp();
			String IP = domain.getIp();
			// 设置页面不缓存
			response.setHeader("Pragma", "No-cache");//指示请求或响应消息不能缓存,禁止浏览器缓存
			response.setHeader("Cache-Control", "no-cache");//与上通常两者合用,Expires实体报头域给出响应过期的日期和时间
			response.setDateHeader("Expires", 0);//设置非法的日期格式,如0

			BufferedImage image = null;
			ServletOutputStream stream = null;
			// 二维码的图片格式
			String format = "gif";
			String content = "";//二维码内容
			//设置二维码大小
			int width2 = 200;
			int height2 = 200;

			Hashtable hints = new Hashtable();
			// 内容所使用编码
			hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

			try {
				BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width2, height2,
						hints);

				int width = bitMatrix.getWidth();
				int height = bitMatrix.getHeight();
				image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
				for (int x = 0; x < width; x++) {
					for (int y = 0; y < height; y++) {
						image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); // 二维码图片为黑白两色
					}
				}
			} catch (Exception e) {
				// TODO: handle exception
			}
			// 只有用这种解码方式才不出现乱码
			String s = "attachment;filename=" + new String("".gif");//二维码的名字
			response.addHeader("Content-Disposition", s);
			/*Content-Disposition为属性名
			disposition-type是以什么方式下载,如attachment为以附件方式下载
			disposition-parm为默认保存时的文件名 
			服务端向客户端游览器发送文件时,使用attachment,这样浏览器会提示保存还是打开*/
			OutputStream os = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("image/gif");
			ImageIO.write(image, format, os);
			os.flush();
			os.close();
	}

这是我的实现代码,每执行一次,就会向客户端页面以文件的形式发送,浏览器会识别它是个文件,自动弹出打开,还是下载的小弹出框,若我有什么地方写错了,或者理解有误,请发现的各位评论指正
 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值