我正在使用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。順便說一句好的問題。 :) –