如何在 Spring 3 中使用 Velocity 工具获取 VelocityEngine?我需要控制器中的一个方法来处理模板 Velocity,但需要有可用于初始化 Spring 3 的 Velocity 工具。现在我正在这样做。
弹簧配置:
<bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="resourceLoaderPath" value="/WEB-INF/velocity/"/>
<property name="velocityProperties">
<props>
<prop key="input.encoding">UTF-8</prop>
<prop key="output.encoding">UTF-8</prop>
</props>
</property>
</bean>
<bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
<property name="cache" value="false"/>
<property name="prefix" value=""/>
<property name="suffix" value=".html"/>
<property name="contentType" value="text/html; charset=UTF-8"/>
<property name="toolboxConfigLocation" value="/WEB-INF/velocity/config/toolbox.xml"/>
<property name="viewClass" value="my.tools.VelocityToolsView"/>
</bean>
在控制器类中:
@Autowired
private VelocityConfigurer configurer;
private VelocityEngine velocityEngine;
private ToolContext toolContext;
@PostConstruct
public void init() {
velocityEngine = configurer.getVelocityEngine();
ToolManager toolManager = new ToolManager();
toolManager.configure("fuulPath/WEB-INF/velocity/config/toolbox.xml");
toolContext = toolManager.createContext();
}
在方法:
VelocityContext velocityContext = new VelocityContext(map, toolContext);
StringWriter writer = new StringWriter();
velocityEngine.mergeTemplate("myTeplate.html", "UTF-8", velocityContext, writer);
String templateString = writer.toString();