How to use Velocity in Web Applications

Introduction, setup and dependencies

This tutorial will show the basic setup steps to make use of Velocity inside of Web Applications.

Please note that this tutorial assumes you aren’t using any additional frameworks that integrate with Velocity, for example, Spring MVC, and it’s meant to illustrate a possible approach to tie together your Java Servlets with Velocity templates.

If you are interested in the main part of the tutorial and already have a project configured, we’d recommend checking Step 4.

What will the tutorial demonstrate?

The tutorial will show a simple web application that has an initial web page with a form for data input, a servlet for processing the data and a web page that will display the processing result.

The view component of the web application will be done using Velocity templates.

What do I need?

If you want to follow the project step-by-step, I’d recommend downloading the code from GitHub using the links on the right hand side. Make sure you start on the step1 branch, but feel free to navigate the repository and check the status of other steps.

After that, import the project into the IDE of your preference.

What tools/libraries will we be using?

The project will make use of the following:

  1. Gradle to build the project (we won’t focus on this, so feel free to download the build.gradle file)

  2. An embedded Jetty server to serve the content

  3. Velocity 2.0 as the template engine to render the view of our web application

If you aren’t familiar with Gradle, the libraries we depend on are added to the project via the build.gradle file, inside the dependencies section:

dependencies {
	providedCompile 'javax.servlet:javax.servlet-api:3.1.0'

	compile 'org.eclipse.jetty:jetty-server:9.4.6.v20170531'
	compile 'org.eclipse.jetty:jetty-servlet:9.4.6.v20170531'

	compile 'org.apache.velocity:velocity-tools:2.0'

	compile 'org.slf4j:slf4j-simple:1.7.25'
}