我正在使用struts-2.3.16,我必须在应用程序中全局禁止来自Freemarker模板的异常。这意味着,我们必须转发到全局jsp来显示一条通用消息,而不是使用来自Freemarker的堆栈跟踪的黄色屏幕,以防止向用户显示堆栈跟踪。对于struts中的泛型异常,我们将全局结果映射到struts.xml中,但它不适用于Freemarker异常。抑制Freemarker模板错误
到目前为止,我已经实施了从What are different ways to handle error in FreeMarker template?的解决方案。所以我创建了一个CustomFreemarkerManager和一个CustomTemplateExceptionHandler。
我CustomFreemarkerManager看起来是这样的:
@Override
public void init(ServletContext servletContext) throws TemplateException {
super.config = super.createConfiguration(servletContext);
super.config.setTemplateExceptionHandler(new CustomTemplateExceptionHandler(servletContext));
super.contentType = "text/html";
super.wrapper = super.createObjectWrapper(servletContext);
if (LOG.isDebugEnabled()) {
LOG.debug("Using object wrapper of class " + super.wrapper.getClass().getName(), new String[0]);
}
super.config.setObjectWrapper(super.wrapper);
super.templatePath = servletContext.getInitParameter("TemplatePath");
if (super.templatePath == null) {
super.templatePath = servletContext.getInitParameter("templatePath");
}
super.configureTemplateLoader(super.createTemplateLoader(servletContext, super.templatePath));
super.loadSettings(servletContext);
}
@Override
protected Configuration createConfiguration(ServletContext servletContext) throws TemplateException {
Configuration configuration = new Configuration();
configuration.setTemplateExceptionHandler(new CustomTemplateExceptionHandler(servletContext));
if (super.mruMaxStrongSize > 0) {
configuration.setSetting("cache_storage", "strong:" + super.mruMaxStrongSize);
}
if (super.templateUpdateDelay != null) {
configuration.setSetting("template_update_delay", super.templateUpdateDelay);
}
if (super.encoding != null) {
configuration.setDefaultEncoding(super.encoding);
}
configuration.setLocalizedLookup(false);
configuration.setWhitespaceStripping(true);
return configuration;
}
在这里,我ServletContext的发到我CustomTemplateExceptionHandler这样我就可以创建一个RequestDispatcher转发给我的exception.jsp。问题是在异常处理程序中,我没有请求和响应,我无法转发到我的jsp。
类CustomTemplateExceptionHandler看起来像这样至今:
private ServletContext servletContext;
public CustomTemplateExceptionHandler(ServletContext servletContext) {
this.servletContext = servletContext;
}
public void handleTemplateException(TemplateException te, Environment env, Writer out) throws TemplateException {
if (servletContext != null) {
RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher("/resources/exception.jsp");
//HERE I have to forward to my jsp
}
}
任何人都知道我该怎么做呢?我希望堆栈跟踪仅在服务器上记录,并且在UI中用普通消息替换堆栈跟踪。
是的,你是对的。您可以尝试使用异常处理程序打印重定向。请参阅http://freemarker.624813.n4.nabble.com/URL-redirect-in-ftl-td625576.html。 –
查看'HTML_DEBUG_HANDLER'如何打印 - https://github.com/apache/incubator-freemarker/blob/2.3-gae/src/main/java/freemarker/template/TemplateExceptionHandler.java#L98。顺便说一句好的问题。 :) –