1 package example;
2
3 import java.util;
4 import java.io;
5 import javax.servlet;
6 import javax.servlet.http;
7 import freemarker.template;
8
9 /**
10 * This Servlet does not do anything useful, just prints "Hello World!". The
11 * intent is to help you to get started if you want to build your own Controller
12 * servlet that uses FreeMarker for the View. For more advanced example, see the
13 * 2nd Web application example.
14 */
15 public class HelloServlet extends HttpServlet {
16 private Configuration cfg;
17
18 public void init() {
19 // Initialize the FreeMarker configuration;
20 // - Create a configuration instance
21 cfg = new Configuration();
22 // - Templates are stoted in the WEB-INF/templates directory of the Web app.
23 cfg.setServletContextForTemplateLoading(
24 getServletContext(), "WEB-INF/templates");
25 // In a real-world application various other settings should be explicitly
26 // set here, but for the sake of brevity we leave it out now. See the
27 // "webapp2" example for them.
28 }
29
30 protected void doGet(HttpServletRequest req, HttpServletResponse resp)
31 throws ServletException, IOException {
32
33 // Build the data-model
34 Map root = new HashMap();
35 root.put("message", "Hello World!");
36
37 // Get the templat object
38 Template t = cfg.getTemplate("test.ftl");
39
40 // Prepare the HTTP response:
41 // - Use the charset of template for the output
42 // - Use text/html MIME-type
43 resp.setContentType("text/html; charset=" + t.getEncoding());
44 Writer out = resp.getWriter();
45
46 // Merge the data-model and the template
47 try {
48 t.process(root, out);
49 } catch (TemplateException e) {
50 throw new ServletException(
51 "Error while processing FreeMarker template", e);
52 }
53 }
54 }