下面列出了org.springframework.web.servlet.view.AbstractView#org.apache.velocity.tools.generic.NumberTool 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void mergeTemplate(String name, String encoding, Map<String, Object> model, StringWriter writer)
throws ResourceNotFoundException, ParseErrorException, Exception {
VelocityContext velocityContext = new VelocityContext(model);
velocityContext.put("dateSymbol", new DateTool());
velocityContext.put("numberSymbol", new NumberTool());
velocityContext.put("mathSymbol", new MathTool());
Template template = engine().getTemplate(name, encoding);
template.merge(velocityContext, writer);
}
/**
* Velocity 模板发送邮件 html 格式
*
* @param to
* @param subject
* @throws javax.mail.MessagingException
*/
public void sendMailVelocity(String from ,String[] to, String subject) throws MessagingException {
//如果不是 html 格式,修改为 SimpleMailMessage
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, StandardCharsets.UTF_8.toString());
/**
*邮件内容
*/
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
//模板内容
Map<String, Object> model = new HashMap<String, Object>();
model.put("firstName", "Yashwant");
model.put("lastName", "Chavan");
model.put("location", "china");
//创建动态 bean
DynaBean dynaBean = new LazyDynaBean();
dynaBean.set("name", "It is name"); //simple
dynaBean.set("gender", new Integer(1)); //simple
//设置 bean 属性
// Velocity 工具类,实例可以直接放入 map ,在模板文件中直接使用
// 如日期格式化 $dateTool.format("yyyy-MM-dd",$info.issueTime)
DateTool dateTool = new DateTool();//日期工具
NumberTool numberTool = new NumberTool();//数字工具
model.put("dateTool",dateTool);
model.put("numberTool",numberTool);
model.put("bean", dynaBean);
String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "./templates/velocity_template_email-newsletter.vm", StandardCharsets.UTF_8.toString(), model);
helper.setText(text, true);
mailSender.send(message);
}
/**
* Initializes Velocity engine
*/
private void init() {
velocityEngine.setProperty(VelocityEngine.RESOURCE_LOADER, "class");
velocityEngine.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
setLogFile();
DateTool dateTool = new DateTool();
dateTool.configure(this.configMap);
MathTool mathTool = new MathTool();
NumberTool numberTool = new NumberTool();
numberTool.configure(this.configMap);
SortTool sortTool = new SortTool();
defaultContext = new VelocityContext();
defaultContext.put("dateTool", dateTool);
defaultContext.put("dateComparisonTool", new ComparisonDateTool());
defaultContext.put("mathTool", mathTool);
defaultContext.put("numberTool", numberTool);
defaultContext.put("sortTool", sortTool);
// Following tools need VelocityTools version 2.0+
//defaultContext.put("displayTool", new DisplayTool());
//defaultContext.put("xmlTool", new XmlTool());
try {
velocityEngine.init();
} catch (Exception e) {
throw new VelocityException(e);
}
}
protected FactoryConfiguration getBaseConfig()
{
FactoryConfiguration base = new FactoryConfiguration();
Data datum = new Data();
datum.setKey("version");
datum.setType("number");
datum.setValue("2.0");
base.addData(datum);
ToolboxConfiguration toolbox = new ToolboxConfiguration();
toolbox.setScope(Scope.REQUEST);
toolbox.setProperty("locale", Locale.US);
ToolConfiguration tool = new ToolConfiguration();
tool.setClass(ResourceTool.class);
toolbox.addTool(tool);
base.addToolbox(toolbox);
toolbox = new ToolboxConfiguration();
toolbox.setScope(Scope.APPLICATION);
tool = new ToolConfiguration();
tool.setKey("calc");
tool.setClass(MathTool.class);
toolbox.addTool(tool);
tool = new ToolConfiguration();
tool.setClass(NumberTool.class);
tool.setProperty("locale", Locale.FRENCH);
toolbox.addTool(tool);
base.addToolbox(toolbox);
return base;
}
public @Test void testEasyConfig()
{
EasyFactoryConfiguration easy = new EasyFactoryConfiguration();
easy.number("version", 2.0);
easy.toolbox("request")
.property("locale", Locale.US)
.tool(ResourceTool.class);
easy.toolbox("application")
.tool("calc", MathTool.class)
.tool(NumberTool.class)
.property("locale", Locale.FRENCH);
assertValid(easy);
assertConfigEquals(getBaseConfig(), easy);
}
public static FactoryConfiguration getConfiguration()
{
EasyFactoryConfiguration easy = new EasyFactoryConfiguration();
easy.number("version", 2.0);
easy.toolbox("request")
.property("locale", Locale.US)
.tool(ResourceTool.class);
easy.toolbox("application")
.tool("calc", MathTool.class)
.tool(NumberTool.class)
.property("locale", Locale.FRENCH);
return easy;
}
private void generateHtmlfile(Map<String, Object> input) {
try{
VelocityEngine ve = new VelocityEngine();
ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
ve.setProperty("classpath.resource.loader.class",ClasspathResourceLoader.class.getName());
ve.init();
Template template = ve.getTemplate("templates/acmeair-report.vtl");
VelocityContext context = new VelocityContext();
for(Map.Entry<String, Object> entry: input.entrySet()){
context.put(entry.getKey(), entry.getValue());
}
context.put("math", new MathTool());
context.put("number", new NumberTool());
context.put("date", new ComparisonDateTool());
Writer file = new FileWriter(new File(searchingLocation
+ System.getProperty("file.separator") + RESULTS_FILE));
template.merge( context, file );
file.flush();
file.close();
}catch(Exception e){
e.printStackTrace();
}
}
@Test
public void testExposeHelpers() throws Exception {
final String templateName = "test.vm";
WebApplicationContext wac = mock(WebApplicationContext.class);
given(wac.getServletContext()).willReturn(new MockServletContext());
final Template expectedTemplate = new Template();
VelocityConfig vc = new VelocityConfig() {
@Override
public VelocityEngine getVelocityEngine() {
return new TestVelocityEngine(templateName, expectedTemplate);
}
};
Map<String, VelocityConfig> configurers = new HashMap<String, VelocityConfig>();
configurers.put("velocityConfigurer", vc);
given(wac.getBeansOfType(VelocityConfig.class, true, false)).willReturn(configurers);
// let it ask for locale
HttpServletRequest req = mock(HttpServletRequest.class);
given(req.getAttribute(View.PATH_VARIABLES)).willReturn(null);
given(req.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE)).willReturn(new AcceptHeaderLocaleResolver());
given(req.getLocale()).willReturn(Locale.CANADA);
final HttpServletResponse expectedResponse = new MockHttpServletResponse();
VelocityView vv = new VelocityView() {
@Override
protected void mergeTemplate(Template template, Context context, HttpServletResponse response) throws Exception {
assertTrue(template == expectedTemplate);
assertTrue(response == expectedResponse);
assertEquals("myValue", context.get("myHelper"));
assertTrue(context.get("math") instanceof MathTool);
assertTrue(context.get("dateTool") instanceof DateTool);
DateTool dateTool = (DateTool) context.get("dateTool");
assertTrue(dateTool.getLocale().equals(Locale.CANADA));
assertTrue(context.get("numberTool") instanceof NumberTool);
NumberTool numberTool = (NumberTool) context.get("numberTool");
assertTrue(numberTool.getLocale().equals(Locale.CANADA));
}
@Override
protected void exposeHelpers(Map<String, Object> model, HttpServletRequest request) throws Exception {
model.put("myHelper", "myValue");
}
};
vv.setUrl(templateName);
vv.setApplicationContext(wac);
Map<String, Class<?>> toolAttributes = new HashMap<String, Class<?>>();
toolAttributes.put("math", MathTool.class);
vv.setToolAttributes(toolAttributes);
vv.setDateToolAttribute("dateTool");
vv.setNumberToolAttribute("numberTool");
vv.setExposeSpringMacroHelpers(false);
vv.render(new HashMap<String, Object>(), req, expectedResponse);
assertEquals(AbstractView.DEFAULT_CONTENT_TYPE, expectedResponse.getContentType());
}
public @Test void testNumberTool() {
NumberTool numberTool = (NumberTool)toolbox.get("number");
assertNotNull(numberTool);
// assertEquals()
}