java - 抑制 Freemarker 模板错误

标签 java struts2 freemarker

我正在使用 struts-2.3.16,并且我必须在我们的应用程序中全局抑制 Freemarker 模板的异常。这意味着,我必须转发到显示通用消息的全局 jsp,而不是显示来自 Freemarker 的堆栈跟踪的黄色屏幕,从而防止向用户显示堆栈跟踪。对于 struts 中的通用异常,我们在 struts.xml 中映射了全局结果,但它不适用于 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 中用通用消息替换堆栈跟踪。

最佳答案

好的,所以我对这个问题的解决方案是在 CustomTemplateExceptionHandler 中的 PrintWriter 上打印与 Freemarker 提供的标准 HTML_DEBUG_HANDLER 类似的响应。查看此链接:

https://github.com/apache/incubator-freemarker/blob/2.3-gae/src/main/java/freemarker/template/TemplateExceptionHandler.java#L98

在这里您可以看到 HTML_DEBUG_HANDLER 是如何管理的。我用一般消息替换了打印堆栈跟踪。 Freemarker 文档建议您使用 RETHROW_HANDLER 并在调用 Template.process() 之后在应用程序中捕获异常。请参阅此处:

http://freemarker.org/docs/app_faq.html#misc.faq.niceErrorPage

但是因为Struts2在后台使用Freemarker,并且Freemarker方法是在action执行之后执行的,所以我不知道如何以及在哪里捕获异常。我已设法在方法handleTemplateException() 中获取HttpServlet 响应和请求(请参阅问题),但我无法转发到我的exception.jsp,因为响应已提交,因此它给了我一个异常。

最终的代码如下所示:

类 CustomFreemarkerManager:

@Override
public void init(ServletContext servletContext) throws TemplateException {
    super.config = super.createConfiguration(servletContext);
    super.config.setTemplateExceptionHandler(new CustomTemplateExceptionHandler());
    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());
    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;
}

类 CustomTemplateExceptionHandler:

public void handleTemplateException(TemplateException te, Environment env, Writer out) throws TemplateException {

    boolean externalPw = out instanceof PrintWriter;
    PrintWriter pw = externalPw ? (PrintWriter) out : new PrintWriter(out);
    try {
        pw.print("<!-- ERROR MESSAGE STARTS HERE -->"
                + "<!-- ]]> -->"
                + "</table></table></table>"
                + "<div align='left' style='"
                + "background-color:#FFFF7C; "
                + "display:block; "
                + "border-top:double; "
                + "padding:10px; "
                + "'>");
        pw.print("<b style='"
                + "color: red; "
                + "font-size:14px; "
                + "font-style:normal; "
                + "font-weight:bold; "
                + "'>"
                + "Oops! We have encountered a problem. Please try again!"
                + "</b>");
        pw.println("</div></html>");
        pw.flush();  // To commit the HTTP response
    } finally {
        if (!externalPw) pw.close();
    }

    throw te;
}

如果有人找到更好的答案,请发布您的答案!

关于java - 抑制 Freemarker 模板错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36129424/

相关文章:

java - 创建名称为 'sessionFactory' 的 bean 时出错

java - Struts 2 使用状态索引

java - Freemarker中如何处理Java抛出的异常?

java - Spring mvc 异常中的 servlet 名称为空

replace - FreeMarker ?替换多个值

java - 希望能够使用Java自动浏览和搜索互联网,无需图形

java - 单个单词的正则表达式

java - 与 Swing : Wait for the UI 同步

java - 音频文件Android

java - Struts 2 中的值未从 jsp 绑定(bind)到操作类