gpt4 book ai didi

java - 如何在 Spring 3 中使用 Velocity Tools 获取 VelocityEngine

转载 作者:行者123 更新时间:2023-12-02 14:38:20 26 4
gpt4 key购买 nike

如何在 Spring 3 中使用 Velocity Tools 获取 VelocityEngine?我需要 Controller 中的一个方法来处理模板 Velocity,但需要有可用于初始化 Spring 3 的 Velocity 工具。现在我就是这样做的。

Spring 配置:

<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>

在 Controller 类中:

@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();

最佳答案

当你不使用 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>

并在你的java类中 Autowiring 这个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);
}
}

关于java - 如何在 Spring 3 中使用 Velocity Tools 获取 VelocityEngine,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14237862/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com