filter中重写应答要素

Java Web中,重写response应答体(响应体)

Java代码   收藏代码
  1. /*** 
  2.      * Send http request 
  3.      *  
  4.      * @param response 
  5.      * @param bytes  :字节数组 
  6.      * @param contentType  :if is null,default value is  "application/json" 
  7.      * @param encoding   :  编码方式 
  8.      * @throws IOException 
  9.      */  
  10.     public static void sendRequestWriter(HttpServletResponse response, byte[] bytes,  
  11.             String contentType,String encoding) throws IOException {  
  12.         response.setContentLength(bytes.length);  
  13.         if (contentType == null) {  
  14.             contentType = "application/json";  
  15.         }  
  16.         response.setContentType(contentType);  
  17.   
  18.         PrintWriter printer = response.getWriter();  
  19.         printer.println(new String(bytes,encoding));  
  20.         printer.flush();  
  21.         printer.close();  
  22.     }  
  23.       
  24.     /*** 
  25.      *  
  26.      * @param response 
  27.      * @param sendData   :<code>String</code> 
  28.      * @param contentType 
  29.      * @param encoding : such as GBK/utf-8 
  30.      * @throws IOException 
  31.      */  
  32.     public static void sendRequestWriter(HttpServletResponse response, String sendData,  
  33.             String contentType,String encoding) throws IOException {  
  34. //      response.setContentLength(sendData.getBytes(encoding).length);  
  35.         byte[]bytes=sendData.getBytes(encoding);  
  36.         sendRequestWriter(response, bytes, contentType, encoding);  
  37.     }  

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

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

Java代码   收藏代码
  1. /*** 
  2.      * test ok 
  3.      * @param response 
  4.      * @param bytes 
  5.      * @param contentType 
  6.      * @param encoding 
  7.      * @throws IOException 
  8.      */  
  9.     public static void sendRequestStream(HttpServletResponse response, byte[] bytes,  
  10.             String contentType) throws IOException {  
  11.         response.setContentLength(bytes.length);  
  12.         if (contentType == null) {  
  13.             contentType = "application/json";  
  14.         }  
  15.         response.setContentType(contentType);  
  16.   
  17.         ServletOutputStream sos = response.getOutputStream();  
  18.         sos.write(bytes, 0, bytes.length);  
  19.         sos.flush();  
  20.         sos.close();  
  21.     }  

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

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值