注意:所有文章除特别说明外,转载请注明出处.
注意:这里自定义FreeMarkerView的目的是为了放一些公共的变量到FreeMarkerView模板里面。
1.配置文件 spring-application.xml
<!-- **********************************************************************
** FreeMaker解析器 **
********************************************************************** -->
<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<!--<property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView" />-->
<property name="viewClass" value="net.mingyang.cms.util.FtlView" />
<property name="contentType" value="text/html;charset=UTF-8" />
<property name="exposeRequestAttributes" value="true" />
<property name="exposeSessionAttributes" value="true" />
<property name="exposeSpringMacroHelpers" value="true" />
<!-- <property name="suffix" value=".ftl" /> -->
<property name="order" value="0" />
</bean>
<bean 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="number_format">0.##########</prop>
<prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
<prop key="date_format">yyyy-MM-dd</prop>
<prop key="classic_compatible">true</prop>
<prop key="template_exception_handler">ignore</prop>
</props>
</property>
</bean>
2.自定义实现类
package cn.edu.xidian.see.ext;
import org.springframework.web.servlet.view.freemarker.FreeMarkerView;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
public class FreeMarkerViewExt extends FreeMarkerView {
private static final String CONTEXT_PATH = "basePath";
@Override
protected void exposeHelpers(Map<String, Object> model, HttpServletRequest request)
throws Exception {
//返回项目根目录
model.put(CONTEXT_PATH, request.getContextPath());
super.exposeHelpers(model, request);
}
}
//或者是这样...
package net.mingyang.cms.util;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.servlet.view.freemarker.FreeMarkerView;
public class FtlView extends FreeMarkerView {
@Override
protected void exposeHelpers(Map<String, Object> model,
HttpServletRequest request) throws Exception {
model.put("contextPath", request.getContextPath());
super.exposeHelpers(model, request);
}
}