Sample Code

Hello World

The sample code below is included in the package distribution.

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

<html>
<head>
<title>Hello World Servlet</title>
</head>

<body bgcolor="#ffffff">

<p>${message}</p>

</body>
</html>

Here's HelloServlet.java, which uses the above template:

package examples;

import java.io.*;
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 {
		super.init(config);
		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 {

		res.setContentType("text/html");
		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 =
                TemplateProcessorParameters.newInstance(out)
                        .withModel(modelRoot);
		template.process(tpp);
		out.close();
	}

	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:

http://localhost:8080/helloworld/.

For other servlet containers, the URL may vary slightly.