新建web工程,新建servlet类:
package com.freemaker.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private Configuration cfg = null;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Template t = cfg.getTemplate("WEB-INF/ftl/helloworld.ftl");
PrintWriter out = response.getWriter();
Map<String, String> dataModel = new HashMap<String, String>();
dataModel.put("username", "yang");
try {
t.process(dataModel, out);
} catch (TemplateException e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
@Override
public void init() throws ServletException {
cfg = new Configuration();
cfg.setServletContextForTemplateLoading(this.getServletContext(), null);
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>freemarker</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>HelloWorldServlet</display-name>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>com.freemaker.servlet.HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/HelloWorldServlet</url-pattern>
</servlet-mapping>
</web-app>
WEB-INF/ftl/helloworld.ftl:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>helloworld</title>
</head>
<body>
<font color=red>${username}</font>
</body>
</html>
可以运行。
但是,如果username为null,就会抛异常:
Expression username is undefined on line 9, column 25 in WEB-INF/ftl/helloworld.ftl. The problematic instruction: ---------- ==> ${username} [on line 9, column 23 in WEB-INF/ftl/helloworld.ftl] ---------- Java backtrace for programmers: ----------