java velocity是什么意思,什么是Apache Velocity?
Can someone please explain, what is Apache Velocity ?
what is its purpose ?
It would be nice to provide an example along with it.
Thanks in advance.
解決方案
Apache Velocity is a template engine. That means that you can add variables to a context, load a template in which those variables are referenced and render a text from this template where the references to the variables are replaced with the variable's actual value.
It's purpose is to separate design and static content from code. Take a website for example. You don't want to create HTML inside your java code, do you? You would have to recompile your app every time you change a bit of design and you would polute your code with unnecessary design clutter. You would rather want to get your variables, either computed or from a database or whatever and have a designer create a HTML template in which your variables are used.
Some pseudo code to make it clear:
/* The user's name is "Foo" and he is of type "admin"*/
User user = getUserFromDatabase("Foo");
/* You would not add hard coded content in real world.
* it is just to show how template engines work */
String message = "Hello,";
Velocity.init(); /* Initialises the Velocity engine */
VelocityContext ctx = new VelocityContext();
/* the user object will be available under the name "user" in the template*/
ctx.put("user",user);
/* message as "welcome" */
ctx.put("welcome",message);
StringWriter writer = new StringWriter();
Velocity.mergeTemplate("myTemplate.vm", ctx, writer);
System.out.println(writer);
Now given a file called myTemplate.vm
${welcome} ${user.name}!
You are an ${user.type}.
The output would be:
Hello, Foo!
You are an admin.
Now let's assume the flat text should be HTML instead. The designer would change myTemplate.vm to
${welcome} ${user.name}
You are an ${user.type}
So the output would be a html page without a single change in the java code.
So the use of a template engines like Velocity (there are others, e.g. Thymeleaf or Freemarker) let designers do a designer's job and programmers do a programmer's job with minimal interference to each other.
總結
以上是生活随笔為你收集整理的java velocity是什么意思,什么是Apache Velocity?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java 画图覆盖_请教如何在java画
- 下一篇: java怎么将加载图片消除_Java中加