使用HttpServletResponseWrapper获取渲染jsp以后的html

   有些场景,我们会试图获取渲染jsp以后的html,或者修改一下生成json,例如把普通的json换成跨域的jsonp。

ResponseFacade只提供了getOutStream(),但是获取不了stream的容器bytearray,不通过hacker的方式根本获取不了。Tomcat也意识到这一点,提供了HttpServletResponseWrapper帮我们解决这个问题,对于HttpServletResponseWrapper有这样的comments:

 

       Provides a convenient implementation of the HttpServletResponse interface

 * that can be subclassed by developers wishing to adapt the response from a

 * Servlet. This class implements the Wrapper or Decorator pattern. Methods

 * default to calling through to the wrapped response object.

 

我们只要在其子类添加一些逻辑就能得到我们想要的东西,用byteArrayOutSteam换掉coyoteOutStream,再通过toByteArray就能获取到html,但这得借助filter帮我们用responsewrapper在dochain()换掉reponse,

上代码吧

/**  
     * Creates a GenericResponseWrapper  
     */ 
    public GenericResponseWrapper(final HttpServletResponse response, final OutputStream outstr) {  
        super(response);  
        this.outstr = new FilterServletOutputStream(outstr);  
    } 

/**  
     * Gets the outputstream.  
     */ 
    public ServletOutputStream getOutputStream() {  
        return outstr;  
    }  


  /**  
     * Gets the print writer.  
     */ 
    public PrintWriter getWriter() throws IOException {  
        if (writer == null) {  
            writer = new PrintWriter(new OutputStreamWriter(outstr, getCharacterEncoding()), true);  
        }  
        return writer;  
    }  
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值