Sample Code

Hello World

The sample code below is included in the package distribution.

Here's a template for a "Hello, World!" servlet:

<title>Hello World Servlet</title>

<body bgcolor="#ffffff">



Here's, which uses the above template:

package examples;

import javax.servlet.*;
import javax.servlet.http.*;
import freemarker.template.*;
import freemarker.template.TemplateFactory;

public class HelloServlet extends HttpServlet {

	private Template template;

	public void init(ServletConfig config) throws ServletException {
		String templatePath = getServletContext().getRealPath("/hello-world.html");
		try {
			template = TemplateFactory.INSTANCE.createFromFile(templatePath);
		} catch (IOException e) {
			throw new UnavailableException( "Can't load template " +
				templatePath + ": " + e.toString() );

	public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws IOException {

		PrintWriter out = res.getWriter();

		// Make a template data model.

		SimpleHash modelRoot = new SimpleHash();
		modelRoot.put("message", new SimpleScalar("Hello, world!"));

		// Process the template.

        TemplateProcessorParameters tpp =

	public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws IOException {
		doGet(req, res);

You can run this servlet with your favorite servlet container. We use Tomcat as our example.

First, build the application using Ant. From the examples directory, type:

ant helloworld

This will create a deploy directory underneath the examples/helloworld directory. You can now deploy the contents of this directory to your application server. For Tomcat, this would be the $TOMCAT_HOME/webapps directory.

Once you've copied the directory, and started the server, you can invoke it with something like:


For other servlet containers, the URL may vary slightly.