next up previous contents
Next: Testing your new hello Up: Using Velocity Previous: Altering

The Velocity helloworld servlet

Now it's time to replace the src/ file with the following source:
   import java.util.Properties;
   import java.util.Vector;

   import javax.servlet.*;
   import javax.servlet.http.*;
   import javax.servlet.ServletConfig;
   import org.apache.velocity.Template;
   import org.apache.velocity.context.Context;
   import org.apache.velocity.servlet.VelocityServlet;
   import org.apache.velocity.exception.ResourceNotFoundException;
   import org.apache.velocity.exception.ParseErrorException;
   public class Hello extends VelocityServlet
     *   Make sure the template files are found
    protected Properties loadConfiguration(ServletConfig config )
        throws IOException, FileNotFoundException
     Properties p = new Properties();
     String path = config.getServletContext().getRealPath("/");
      if (path == null)
       System.out.println(" SampleServlet.loadConfiguration() : unable to " 
                          + "get the current webapp root.  Using '/'. Please fix.");
       path = "/";
      p.setProperty( Velocity.FILE_RESOURCE_LOADER_PATH,  path );
      p.setProperty( "runtime.log", path + "hello_velocity.log" );
      return p;
     * The Servlet
    public Template handleRequest(HttpServletRequest request, 
                                  HttpServletResponse response, Context ctx )
     Template outty = null;
     String text = "Hello World";
     ctx.put("variable", text);
     try {
       // Open the template 'hello.vm'
       outty =  getTemplate("hello.vm");
     } catch( ParseErrorException pee ){
       System.out.println("SampleServlet : parse error for template " + pee);
     } catch( ResourceNotFoundException rnfe ){
       System.out.println("SampleServlet : template not found " + rnfe);
     } catch( Exception e ){
       System.out.println("Error " + e);
     return outty;
And try to build it:
   marloes@escay sample]$ ./
   Searching for build.xml ...
   Buildfile: /home/marloes/sample/build.xml
       [javac] Compiling 1 source file to /usr/tomcat/webapps/myapp2/WEB-INF/classes
   Total time: 18 seconds
   [marloes@escay sample]$

The Servlet needs a hello.vm template! Create a template:

     <title>Hello Template</title>
   <body bgcolor="#ffac00" text="black" link="blue" alink="green" vlink="red">
        $variable !
Store the template in the /web directory.

The hello.vm file has a variable $variable. The servlet opens the hello.vm file replaces the $variable field with "Hello World" and returns the html file.

Build the project again. The hello.vm file is copied from your web directory to the /usr/tomcat/webapps/myapp/ directory. Now it's time to test the Velocity servlet!

Copyright © 2001, R.M. Morriën, H.P.A.M. Snoek, M.A.C. Bakker