How to use Velocity in Web Applications

Using Velocity to render the view

Adding the Velocity template to the name processing

In the last step, we added a servlet that processes the name but doesn’t yet use Velocity to render the View that we want to present to our users.

We’ll define a new name.vm Velocity template that will display the processed name and also the length of the string.

		<title>Processed Name</title>
		$!processedName with $!numberOfCharacters characters

The processedName and numberOfCharacters that are referenced in the Velocity template aren’t yet available, so we need to update our NameServlet to include them.

Updating our NameServlet

As mentioned above, we need to include the 2 attributes being referenced by our Velocity template, and also need to tell the servlet to make use of the name.vm template.

For this, we’ll update our NameServlet with the following:

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String title = req.getParameter("title");
    String firstName = req.getParameter("firstName");
    String lastName = req.getParameter("lastName");

    String processedName = String.format("%s %s %s", title, firstName, lastName).toUpperCase();

    // add attributes that can be used by the Velocity template (e.g. using $processedName)
    req.setAttribute("processedName", processedName);
    req.setAttribute("numberOfCharacters", processedName.length());

    // forward the request to the Velocity template, using a dispatcher
    // (this is really the main part that connects our View with the VelocityViewServlet)
    RequestDispatcher dispatcher = req.getRequestDispatcher("/name.vm");
    dispatcher.forward(req, resp);

Testing our setup

If you try running the application again, after filling the form and clicking Submit you should now get the view rendered by Velocity as defined in our name.vm template, for example:

Example Response