我为JSP配置了一个过滤器。在过滤器中,我使用HTTPResponseWrapper来修改对用户的响应。我在Filter的doFilter方法中的代码是:
CharArrayWrapper responseWrapper = new CharArrayWrapper(
(HttpServletResponse) response);
chain.doFilter(request, responseWrapper);
String responseString = responseWrapper.toString();
System.out.println("responseString ********************* "
+ responseString);
PrintWriter out = response.getWriter();
out.write(responseString);
CharArrayWrapper类是:
public class CharArrayWrapper extends HttpServletResponseWrapper {
private CharArrayWriter charWriter;
public CharArrayWrapper(HttpServletResponse response) {
super(response);
charWriter = new CharArrayWriter();
}
public PrintWriter getWriter() {
return (new PrintWriter(charWriter));
}
public String toString() {
return (charWriter.toString());
}
public char[] toCharArray() {
return (charWriter.toCharArray());
}
}
如果配置了上述过滤器的JSP执行正常,过滤器也没有问题,我可以在控制台上看到sysout。
另一方面,当JSP scriptlet代码(它是一个旧的应用程序)中引发了一些未处理的异常并且我调用了chain.doFilter(request,responseWrapper);时,我得到一个NullPointerException。有什么方法可以让我在过滤器中知道JSP中有一个未处理的异常
答案 0 :(得分:0)
您可以将代码简单地包装在try catch
块中,如下所示:
CharArrayWrapper responseWrapper = new CharArrayWrapper((HttpServletResponse) response);
try {
chain.doFilter(request, responseWrapper);
String responseString = responseWrapper.toString();
System.out.println("responseString ********************* " + responseString);
PrintWriter out = response.getWriter();
out.write(responseString);
} catch (Exception e) {
// do whatever is necessary (logging etc.)
}
还有其他一些事情需要考虑:
getWriter
总是会创建一个新的PrintWriter
,这可能会导致一些副作用,因为其他组件也可能会调用getWriter
。我创建了一个实例变量。