filter应用 (三)

2014-11-24 09:49:26 · 作者: · 浏览: 2
/**
* Wrapper:在内存中开辟一个ByteOutputStream,然后将拦截的响应写入byte[],
* 写入完毕后,再将wrapper的byte[]写入真正的response对象
* This class is used for wrapped response for getting cached data.
*/
class CachedResponseWrapper extends HttpServletResponseWrapper {

/**
* Indicate that getOutputStream() or getWriter() is not called yet.

*/
public static final int OUTPUT_NONE = 0;

/**
* Indicate that getWriter() is already called.
*/
public static final int OUTPUT_WRITER = 1;

/**
* Indicate that getOutputStream() is already called.
*/
public static final int OUTPUT_STREAM = 2;

private int outputType = OUTPUT_NONE;

private int status = SC_OK;

private ServletOutputStream output = null;

private PrintWriter writer = null;

private ByteArrayOutputStream buffer = null;

public CachedResponseWrapper(HttpServletResponse resp) throws
IOException {
super(resp);
buffer = new ByteArrayOutputStream();
}

public int getStatus() {
return status;
}

public void setStatus(int status) {
super.setStatus(status);
this.status = status;
}

public void setStatus(int status, String string) {
super.setStatus(status, string);
this.status = status;
}

public void sendError(int status, String string) throws IOException
{
super.sendError(status, string);
this.status = status;
}

public void sendError(int status) throws IOException {
super.sendError(status);
this.status = status;
}

public void sendRedirect(String location) throws IOException {
super.sendRedirect(location);
this.status = SC_MOVED_TEMPORARILY;
}

public PrintWriter getWriter() throws IOException {
if (outputType == OUTPUT_STREAM)
throw new IllegalStateException();
else if (outputType == OUTPUT_WRITER)
return writer;
else {
outputType = OUTPUT_WRITER;
writer = new PrintWriter(new OutputStreamWriter(buffer,
getCharacterEncoding()));
return writer;
}
}

public ServletOutputStream getOutputStream() throws IOException {

if (outputType == OUTPUT_WRITER)
throw new IllegalStateException();
else if (outputType == OUTPUT_STREAM)
return output;
else {