rdm*_*rdm 2 java spring velocity
如何在Spring 3中使用VelocityEngine和Velocity Tools?我需要一个控制器中的方法来处理模板Velocity,但需要有可用于初始化Spring 3的Velocity Tools.现在我这样做了.
弹簧配置:
<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>
Run Code Online (Sandbox Code Playgroud)
在控制器类中:
@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();
}
Run Code Online (Sandbox Code Playgroud)
在方法中:
VelocityContext velocityContext = new VelocityContext(map, toolContext);
StringWriter writer = new StringWriter();
velocityEngine.mergeTemplate("myTeplate.html", "UTF-8", velocityContext, writer);
String templateString = writer.toString();
Run Code Online (Sandbox Code Playgroud)
当你不使用Spring配置时,上面获得速度的方法很好.当你使用Spring时,你不需要这么多的复杂性.
在spring.xml中定义这个bean
<bean id="velocityEngine"
class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="velocityProperties">
<value>
resource.loader=class
class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
</value>
</property>
</bean>
Run Code Online (Sandbox Code Playgroud)
在你的java类中自动装配这个bean
@Component
public class Sample {
private VelocityEngine velocityEngine;
public VelocityEngine getVelocityEngine() {
return velocityEngine;
}
@Autowired
@Required
public void setVelocityEngine(VelocityEngine velocityEngine) {
this.velocityEngine = velocityEngine;
}
public String getSomething(Object variable) {
Map model = new HashMap();
model.put("variable",variable);
return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "/templates/sometemp.vm", model);
}
}
Run Code Online (Sandbox Code Playgroud)