freemarker 异常处理
SSH2处理方案:
freemarker文件如果出错,网站的前台页面会报出很明显的错误-焦黄的背景,血红的文字,很不利于用户体验的。如何修改这个问题呢?
首先需要在struts.xml配置文件里添加下面一行代码:
1
|
<constant name="struts.freemarker.manager.classname" value="net.swiftlet.freemarker.MyFreemarkerManager" />
|
接着新建MyFreemarkerManager类,如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
public class MyFreemarkerManager extends org.apache.struts2.views.freemarker.FreemarkerManager
{
private static final Logger LOG = LoggerFactory.getLogger(MyFreemarkerManager.class);
public void init(ServletContext servletContext) throws TemplateException
{
config = createConfiguration(servletContext);
config.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
contentType = DEFAULT_CONTENT_TYPE;
wrapper = createObjectWrapper(servletContext);
if (LOG.isDebugEnabled())
{
LOG.debug("Using object wrapper of class " + wrapper.getClass().getName());
}
config.setObjectWrapper(wrapper);
templatePath = servletContext.getInitParameter(INITPARAM_TEMPLATE_PATH);
if (templatePath == null)
{
templatePath = servletContext.getInitParameter("templatePath");
}
configureTemplateLoader(createTemplateLoader(servletContext, templatePath));
loadSettings(servletContext);
}
}
|
SpringMVC-Freemarker异常配置
1、spring mvc的异常配置
spring mvc 提供了SimpleMappingExceptionResolver来处理异常,这里的只是由web 请求,经由controller引发的异常,无法处理freemarker的异常
2、freemarker自定义异常
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
/** * 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
< 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
1
2
3
4
5
|
<!--配置freemarker异常--> < error-page > < exception-type >com.persia.exception.ViewException</ exception-type > < location >/WEB-INF/views/error/viewException.ftl</ location > </ error-page > |