之前遇到一个问题,想把outputstream修改一下.因为这是个输出流,想要改这个里面的东西不是这么简单的.
sun为我们提供了这么一个工具HttpServletResponseWrapper抽象类,利用这个类的子类把servletresponse包装一下,在过滤器中使用,就可以去除response的文件流,对其作出修改.给出一个实现:
Java代码
- package com.ali.report.birt.filter;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.OutputStreamWriter;
- import java.io.PrintWriter;
- import java.io.UnsupportedEncodingException;
- import javax.servlet.ServletOutputStream;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpServletResponseWrapper;
- public class CharResponseWrapper extends HttpServletResponseWrapper {
- private ByteArrayOutputStream buffer=null;
- private ServletOutputStream out=null;
- private PrintWriter writer=null;
- public CharResponseWrapper(HttpServletResponse resp) throws IOException{
- super(resp);
- buffer=new ByteArrayOutputStream();//真正存储数据的流
- out=new WapperedOutputStream(buffer);
- writer=new PrintWriter(new OutputStreamWriter(buffer,this.getCharacterEncoding()));
- }
- //重载父类获取outputstream的方法
- @Override
- public ServletOutputStream getOutputStream()throws IOException{
- return out;
- }
- //重载父类获取writer的方法
- @Override
- public PrintWriter getWriter() throws UnsupportedEncodingException{
- return writer;
- }
- //重载父类获取flushBuffer的方法
- @Override
- public void flushBuffer()throws IOException{
- if(out!=null){
- out.flush();
- }
- if(writer!=null){
- writer.flush();
- }
- }
- @Override
- public void reset(){
- buffer.reset();
- }
- public String getContent()throws IOException{
- flushBuffer();//将out、writer中的数据强制输出到WapperedResponse的buffer里面,否则取不到数据
- return new String(buffer.toByteArray());
- }
- //内部类,对ServletOutputStream进行包装
- private class WapperedOutputStream extends ServletOutputStream{
- private ByteArrayOutputStream bos=null;
- public WapperedOutputStream(ByteArrayOutputStream stream) throws IOException{
- bos=stream;
- }
- @Override
- public void write(int b) throws IOException{
- bos.write(b);
- }
- }
- }
然后在你的过滤器中这么使用:
Java代码
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
- CharResponseWrapper crw = new CharResponseWrapper((HttpServletResponse)response);
- chain.doFilter(request, crw);
- String content = crw.getContent();//response流的内容
- //此处可以对content做处理,然后再把content写回到输出流中
- response.setContentLength(-1);
- PrintWriter out = response.getWriter();
- content = this.changeContent(content, sessionid, folder);
- out.write(content);
- out.flush();
- out.close();*/
- }
如此这般就可以达到你的目的了,当然扩展一下还是可以干很多事的,比如说压缩图片,改变字符集..........