Freemarker template error handling with Spring MVC

2019-06-04 06:35发布

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>

3条回答
女痞
2楼-- · 2019-06-04 07:03

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
查看更多
再贱就再见
3楼-- · 2019-06-04 07:13

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; 
}
查看更多
Summer. ? 凉城
4楼-- · 2019-06-04 07:16

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>
查看更多
登录 后发表回答