How can I check if a response (ServletResponse
) contains any content without calling the getWriter()
- method, e. g. in a filter? Or in other words: the filter should only modify the content if there was already written something into the stream:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// Only do that if there is really some content
PrintWriter out = response.getWriter();
It could happen that the response.getWriter()
- method might be called later on somewhere else in the code (not in this filter, e. g. for a file-download). In that case, the second call will fail since the stream was already opened...
One way is to extend ServletResponseWrapper
and use a CharArrayWriter
internally for writing the response. The CharArrayWriter
has a size()
method which will return the size of the buffer. Make sure you pass a wrapped response down the filter chain and you should be able to get the size at any point in the program.
public class LengthAwareServletResponseWrapper extends ServletResponseWrapper {
private final CharArrayWriter out = new CharArrayWriter();
public LengthAwareServletResponseWrapper(final ServletResponse response) {
super(response);
}
public int getWrittenContentLength() {
return out.size();
}
@Override
public PrintWriter getWriter() throws IOException {
return new PrintWriter(out);
}
}
How can I check if a response (ServletResponse
) contains any content without calling the getWriter()
- method, e. g. in a filter? Or in other words: the filter should only modify the content if there was already written something into the stream:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// Only do that if there is really some content
PrintWriter out = response.getWriter();
It could happen that the response.getWriter()
- method might be called later on somewhere else in the code (not in this filter, e. g. for a file-download). In that case, the second call will fail since the stream was already opened...
One way is to extend ServletResponseWrapper
and use a CharArrayWriter
internally for writing the response. The CharArrayWriter
has a size()
method which will return the size of the buffer. Make sure you pass a wrapped response down the filter chain and you should be able to get the size at any point in the program.
public class LengthAwareServletResponseWrapper extends ServletResponseWrapper {
private final CharArrayWriter out = new CharArrayWriter();
public LengthAwareServletResponseWrapper(final ServletResponse response) {
super(response);
}
public int getWrittenContentLength() {
return out.size();
}
@Override
public PrintWriter getWriter() throws IOException {
return new PrintWriter(out);
}
}
0 commentaires:
Enregistrer un commentaire