Jim
Jim

Reputation: 19582

When to use Velocity?

I recently read about Velocity. I also read the tutorial here.
But I can not understand what is the advantage of using Velocity.As far as I can tell we can do the same things using JSP tags.
So when one would introduce Velocity in his project and to gain what?

Upvotes: 2

Views: 1223

Answers (3)

Sergiu Dumitriu
Sergiu Dumitriu

Reputation: 11611

Velocity is a templating engine, JSP is (kind of) a scripting engine. The differences are quite major, although at first sight it would seem that they do the same thing, and you can abuse Velocity to really turn it into a scripting engine. The two main differentiators IMHO are:

  • Velocity is more secure: by default it only lets you call only public methods of the objects that you specifically put in the context; JSP lets you execute almost any Java code
  • Velocity is easier to understand: it has a simple syntax with very few syntax elements; JSP has the full Java syntax inside its scriptlet tags, plus the <% wrappers %>

So, neither one is clearly better than the other in all situations, you have to decide for yourself when you should use each one, and yes, they can be combined in the same project for different purposes.

IMHO Velocity works best in the following cases:

  • Simple interpolation of a template with a few variables passed in the context, for example email templates
  • I think that Velocity is a better candidate for implementing a very clean View part of a MVC architecture, since in JSP it is more tempting to mix some code (Controller) inside the JSP pages, and in the end you mix both the view and the controller in JSP pages.
    • Another advantage is that its syntax can be understood by non-developers, so both interface designers and developers can work on the same files
  • It works well enough as a secure scripting engine that you can use for running user-generated code.

Upvotes: 3

David
David

Reputation: 375

Say you want to create a dynamic file, say a HTML file. You can either write the file in code and att the tags like

<body>
"<div>User:" + users.getUserName() + "</div>"
</body>

Or you can use Velocity to create a template file

<body>
<div>User: #user.getUserName()</div>
</body>

The benefit of doing this is that you seperate the file from the code, ie you can modify it afterwards without recompiling the code.

Upvotes: 1

dcernahoschi
dcernahoschi

Reputation: 15250

You can use it whenever you need a template for something. For example your application might send text emails to customers and an email has to be customized like this:

Dear $customerName

We announce you that tomorrow $tomorrowDate the following accounts:

   #foreach ($accounts in $account)

With Velocity you can create a few email templates and than customize their content for every customer. You don't have to use it as a replacement for JSP.

Upvotes: 2

Related Questions