Java Tutorial - Java Script :
Velocity
You will notice that the format is similar to that of the WebMacro template; basically, the only difference in this trivial example is that there is no need for a directive to set the content type. Also, similarly to the WebMacro template, the $myCity variable is expanded by the application prior to being presented
to the user. The Velocity HelloMyCity servlet looks like this:
import java.io.*;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.http.*;
import org.apache.velocity.Template;
import org.apache.velocity.context.Context;
import org.apache.velocity.servlet.VelocityServlet;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.exception.ParseErrorException;
public class HelloMyCity extends VelocityServlet
{
// Configure so that templates will be found in the application root
protected Properties loadConfiguration(ServletConfig config )
throws IOException, FileNotFoundException
{
Properties p = new Properties();
String path = config.getServletContext().getRealPath(“/”);
if (path == null)
{
path = “/”;
}
p.setProperty( Velocity.FILE_RESOURCE_LOADER_PATH, path );
return p;
}
public Template handleRequest( HttpServletRequest request,
HttpServletResponse response, Context ctx )
{
String myCity = request.getParameter(“myCity”);
if(myCity == null)
myCity = “Fort Myers ”;
ctx.put(“myCity”, myCity );
// Get the template.
Template out = null;
try
{
out = getTemplate(“HelloMyCity.vm”);
}catch( ParseErrorException pee )
{
System.out.println(“HelloMyCity : template error”);
}catch( ResourceNotFoundException rnfe )
{
System.out.println(“HelloMyCity : template not found”);
}catch( Exception e )
{
System.out.println(“Error “ + e);
}
return out;
}
}
The loadConfiguration(ServletConfig) method is called by init() of the superclass, enabling you to configure the location for templates; in this case, the application root. The main workhorse is the handleRequest (HttpServletRequest, HttpServletResponse,Context) method. You can see that this is very similar to the doGet and doPost methods of a conventional servlet, except for the addition of the Context parameter. After we retrieve the value for the parameter and check its value, we put it into the Context. We then define our template and return it so that it can be merged with the data context before it is presented to the user. We invoke our Velocity
application as follows: http://localhost:8080/velocity/servlet/HelloMyCity The result should look like Figure 6.10
As you can see from this short presentation, Velocity is a very capable player in the template engine space. In fact, Velocity has become so popular so quickly that it has generated some lively discussions on Web forums, particularly regarding its comparison to WebMacro. In the next section, will make our selection, comparing Velocity with WebMacro and Tea.
