我已经扩展了DispatchAction
来创建我自己的CustomDispatch
类,其中包含被覆盖的execute()
方法。
我想以某种方式获得在Action
中定义的方法中写入response.getWriter()
的响应文本。我只能访问HttpServletResponse
对象,而不能访问写入响应的文本。
请帮帮我。
发布于 2018-07-21 05:44:22
您可以使用ServletResponseWrapper
截取写操作,并将它们放入您自己的缓冲区中,以便在需要时进行检索。
例如,您可以从以下内容开始:
public class WrappingFilter implements Filter
{
private static final ThreadLocal<StringBuilder> contentBuffer = new ThreadLocal<>();
@Override
public void init(final FilterConfig filterConfig) throws ServletException
{
}
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException, ServletException
{
contentBuffer.set(new StringBuilder());
chain.doFilter(request, new ContentBufferingResponseWrapper(response));
contentBuffer.remove();
}
@Override
public void destroy()
{
}
public static StringBuilder getResponse()
{
return contentBuffer.get();
}
private class ContentBufferingResponseWrapper extends ServletResponseWrapper
{
public ContentBufferingResponseWrapper(final ServletResponse response)
{
super(response);
}
@Override
public PrintWriter getWriter() throws IOException
{
return new PrintWriter(super.getWriter())
{
@Override
public void write(final String s, final int off, final int len)
{
contentBuffer.get().append(s);
super.write(s, off, len);
}
};
}
}
}
然后,您可以调用WrappingFilter.getResponse()
来获取到目前为止为当前请求编写的响应的缓冲区。
这不是一个优雅的解决方案,我也没有对它进行测试,但希望能让您走上正确的道路。
我建议你看一下sitemesh,它使用类似的方法将响应截获到不同的缓冲区中,以便可以在写入响应之前对其进行修改-这与您试图做的事情略有不同,但也可以应用相同的技术。https://github.com/sitemesh/sitemesh3/blob/master/sitemesh/src/main/java/org/sitemesh/webapp/contentfilter/HttpServletResponseBuffer.java
https://stackoverflow.com/questions/50818413
复制相似问题