1、spring mvc的异常配置
spring mvc 提供了SimpleMappingExceptionResolver来处理异常,这里的只是由web 请求,经由controller引发的异常,无法处理freemarker的异常
2、freemarker自定义异常
/**
* freemarker页面上的异常控制
* 在webmvc-config.xml里面的freemarkerSettings里头配置
* @author scipio
* @created 2014-02-01
*/
public class FreemarkerExceptionHandler implements TemplateExceptionHandler {
private static final Logger log = LoggerFactory
.getLogger(FreemarkerExceptionHandler.class);
public void handleTemplateException(TemplateException te, Environment env,
Writer out) throws TemplateException {
log.warn("[Freemarker Error: " + te.getMessage() + "]");
throw new ViewException("freemarker error",te);
}
}
这里重新包装异常抛出(这种方式要求比较严格,因为freemarker对个别的错误,比如某个变量没有定义,可以忽略,只是后台抛异常,然后整个页面还是会渲染出来)
3、配置HtmlFreeMarkerConfigurer
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/views/"/>
<property name="freemarkerSettings">
<props>
<prop key="template_update_delay">0</prop>
<prop key="default_encoding">UTF-8</prop>
<prop key="locale">zh_CN</prop>
<prop key="url_escaping_charset">UTF-8</prop>
<prop key="whitespace_stripping">true</prop>
<prop key="number_format">#</prop>
<!-- 配置自定义的freemarker异常处理-->
<prop key = "template_exception_handler">com.persia.exception.FreemarkerExceptionHandler</prop>
</props>
</property>
</bean>
4、针对该异常,配置web.xml
<!--配置freemarker异常-->
<error-page>
<exception-type>com.persia.exception.ViewException</exception-type>
<location>/WEB-INF/views/error/viewException.ftl</location>
</error-page>
来源:oschina
链接:https://my.oschina.net/u/1383356/blog/200447