一直使用jsp作为前段的渲染器,今天试了一下FreeMaker和SpringMVC的整合,发现蛮简单的,现总结记录如下

1. applicationContext.xml增加内容

<!– freemarker的配置 –>
<bean id=”freemarkerConfigurer”
class=”org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer”>
<property name=”templateLoaderPath” value=”/WEB-INF/jsp/” />
<property name=”defaultEncoding” value=”UTF-8″ />
<property name=”freemarkerSettings”>
<props>
<prop key=”template_update_delay”>10</prop>
<prop key=”locale”>zh_CN</prop>
<prop key=”datetime_format”>yyyy-MM-dd HH:mm:ss</prop>
<prop key=”date_format”>yyyy-MM-dd</prop>
<prop key=”number_format”>#.##</prop>
</props>
</property>
</bean>

<!– FreeMarker视图解析 如返回userinfo。。在这里配置后缀名ftl和视图解析器。。 –>
<bean id=”viewResolver”
class=”org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver”>
<!– 下面的设置为解决base变量的获取 –>
<property name=”viewClass” value=”com.useol.util.MyFreeMakerView” />
        <property name=”suffix” value=”.html” />
<property name=”contentType” value=”text/html;charset=UTF-8″ />
<property name=”exposeRequestAttributes” value=”true” />
<property name=”exposeSessionAttributes” value=”true” />
<property name=”exposeSpringMacroHelpers” value=”true” />
</bean>

<bean id=”messageSource”
class=”org.springframework.context.support.ResourceBundleMessageSource”
p:basename=”i18n/messages” />

2. 其中MyFreeMakerView类为解决springmvc和freemaker整合后,获取basepath,即context目录的问题,源码如下:

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.useol.util;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.servlet.view.freemarker.FreeMarkerView;

/**
*
* @author duyaofei
*/
public class MyFreeMakerView extends FreeMarkerView {

private static final String CONTEXT_PATH = “base”;

@Override
protected void exposeHelpers(Map model,
HttpServletRequest request) throws Exception {
model.put(CONTEXT_PATH, request.getContextPath());
super.exposeHelpers(model, request);
}
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注