The "Hello, World" Example

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}

</body>
</html>
	

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

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import freemarker.template.*;

public class HelloServlet extends HttpServlet {

        TemplateCache templateCache = new FileTemplateCache(HelloServlet.class);

	public void doGet(HttpServletRequest req, HttpServletResponse res)
		throws ServletException, 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!"));
                Template template = templateCache.getTemplate("hello-world.html");
		// Process the template.
		try {
			template.process(modelRoot, out);
		} catch( TemplateException e ) {
			// Failure case
		}
		
		out.close();
	}

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

There is now an ant build target that builds this example, as well as the guestbook example into a .war file. You simply type:

   ant war

on the command line and it will build an fmexamples.war. You will deploy this by dropping the file into the appropriate directory. If you are using Tomcat, that is <TOMCAT_HOME>/webapps. Then, you should be able to run the servlet by opening the URL:

   http://localhost:8080/fmexamples/servlet/hello

in a browser. The above URL assumes that you are running Tomcat in its default out-of-the-box configuration. For other servlet servers, you may have to change the above slightly.