ServletResponse和HttpServletResponseWrapper之间的区别?
我是servlet的新手,正在阅读一些关于过滤器和包装器的文本。我可以理解过滤器,但对包装器感到困惑。在书中,作者举了一个例子:
如果没有包装器:
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
String name = request.getParameter("name").trim();
try {
chain.doFilter(request, response);
PrintWriter out = response.getWriter();
if (name.length() == 0) {
out.println("Some message");
out.println("</body>");
out.println("</html>");
out.close();
}
} catch (Throwable t) {
}
}
在包装器的情况下:
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
String name = request.getParameter("name").trim();
HttpServletResponse httpRes = (HttpServletResponse) response;
HttpServletResponseWrapper resWrapper = new HttpServletResponseWrapper(httpRes);
try {
chain.doFilter(request, response);
PrintWriter out = resWrapper.getWriter(); // why dont we just use response.getWriter();
if (name.length() == 0) {
out.println("<h3>Some message");
out.println("</body>");
out.println("</html>");
out.close();
}
} catch (Throwable t) {
}
}
为什么我们需要,而我们可以在案例1中做同样的事情?任何人都可以给我一个我们必须使用的明确例子来代替?我试图谷歌,但没有找到运气。HttpServletResponseWrapper
ServletResponse
HttpServletResponseWrapper
ServletResponse