What is Apache Velocity? [closed] Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of What is Apache Velocity? [closed] without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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*/
/* message as "welcome" */

StringWriter writer = new StringWriter();

Velocity.mergeTemplate("myTemplate.vm", ctx, 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

  <h1>${welcome} ${user.name}</h1>
  <p>You are an ${user.type}</p>

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.

We are here to answer your question about What is Apache Velocity? [closed] - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji