Freemarker template error handling with Spring MVC

有些话、适合烂在心里 提交于 2019-12-08 05:04:41

问题


I am using Freemarker template with Spring MVC. Is there a way to return HTTP Status 500 if there is any error rendering the template?

Currently I am using attempt block to handle error, but would like to throw Internal Server error and allow web server to redirect to a default error page

<#attempt>
  attempt block
<#recover>
  recover block
</#attempt>

Below is my servlet-context.xml

<beans:bean id="viewResolver"
    class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
    <beans:property name="cache" value="true" />
    <beans:property name="prefix" value="" />
    <beans:property name="contentType" value="text/html; charset=UTF-8" />
    <beans:property name="suffix" value=".ftl" />
    <beans:property name="exposeSessionAttributes" value="true" />
</beans:bean>

回答1:


Below change in servlet-context.xml resolved the issue. Now it throws HTTP 500 error which is intercepted by web server and I am able to mast the message by redirecting to pre-defined error page.

<beans:bean id="freemarkerConfig"
        class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <beans:property name="templateLoaderPath" value="/WEB-INF/ftl/" />
        <beans:property name="freemarkerSettings">
            <beans:props>
                <beans:prop key="template_exception_handler">rethrow</beans:prop>
            </beans:props>
        </beans:property>
    </beans:bean>



回答2:


This is the java-based equivalent configuration:

@Bean 
public FreeMarkerConfigurer freemarkerConfig() throws TemplateException { 
    FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer(); 
    freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/views/ftl/");

    Properties settings = new Properties();
    settings.setProperty(freemarker.template.Configuration.TEMPLATE_EXCEPTION_HANDLER_KEY, "rethrow");
    freeMarkerConfigurer.setFreemarkerSettings(settings);
    return freeMarkerConfigurer; 
}



回答3:


A simple way to change the mode from "debug" to "rethrow" is to configure it in your application.properties:

spring.freemarker.settings.template_exception_handler=rethrow


来源:https://stackoverflow.com/questions/30426788/freemarker-template-error-handling-with-spring-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!