filter中重写应答要素

本文介绍了在JavaWeb中如何重写HTTP响应体的方法,包括使用PrintWriter和ServletOutputStream两种方式,并提供了具体实现代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java web中,重写response应答体(响应体)

/***
	 * Send http request
	 * 
	 * @param response
	 * @param bytes  :字节数组
	 * @param contentType  :if is null,default value is  "application/json"
	 * @param encoding   :  编码方式
	 * @throws IOException
	 */
	public static void sendRequestWriter(HttpServletResponse response, byte[] bytes,
			String contentType,String encoding) throws IOException {
		response.setContentLength(bytes.length);
		if (contentType == null) {
			contentType = "application/json";
		}
		response.setContentType(contentType);

		PrintWriter printer = response.getWriter();
		printer.println(new String(bytes,encoding));
		printer.flush();
		printer.close();
	}
	
	/***
	 * 
	 * @param response
	 * @param sendData   :<code>String</code>
	 * @param contentType
	 * @param encoding : such as GBK/utf-8
	 * @throws IOException
	 */
	public static void sendRequestWriter(HttpServletResponse response, String sendData,
			String contentType,String encoding) throws IOException {
//		response.setContentLength(sendData.getBytes(encoding).length);
		byte[]bytes=sendData.getBytes(encoding);
		sendRequestWriter(response, bytes, contentType, encoding);
	}

 以上方法都是使用PrintWriter来写入response的。

下面的方式是使用流的方式写入response:

/***
	 * test ok
	 * @param response
	 * @param bytes
	 * @param contentType
	 * @param encoding
	 * @throws IOException
	 */
	public static void sendRequestStream(HttpServletResponse response, byte[] bytes,
			String contentType) throws IOException {
		response.setContentLength(bytes.length);
		if (contentType == null) {
			contentType = "application/json";
		}
		response.setContentType(contentType);

		ServletOutputStream sos = response.getOutputStream();
		sos.write(bytes, 0, bytes.length);
		sos.flush();
		sos.close();
	}

 应用:用于在网关中进行请求转发和响应。

见附件中的类com.common.util.SystemUtil

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值