1.在WebRoot目录下新建一个templates文件夹,再建立一个test.ftl文件
<%@ page language="java" import="java.util.*,java.sql.*,com.test.*" pageEncoding="GB2312" isELIgnored="false"%>
<%@ taglib prefix="s" uri="/WEB-INF/classes/oscache.tld" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
${message}
</body>
</html>
2.新建一个LoginServlet
package com.test;
import java.io.IOException;
import java.io.Writer;
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;
public class LoginServlet extends HttpServlet {
/**
* Constructor of the object.
*/
private Configuration cfg;
public LoginServlet() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void init() throws ServletException {
cfg = new Configuration();
cfg.setServletContextForTemplateLoading(this.getServletContext(),"WEB-INF/templates");
//这个地方与JAVA的调用方式不用,第一个参数放的是WEB应用的ServletContext实例,第二个参数放的是模板的路径
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Map root = new HashMap();
root.put("message","Hello FreeMaker");
Template t = cfg.getTemplate("test.ftl");
resp.setContentType("text/html;charset="+t.getEncoding());
Writer out = resp.getWriter();//通过获得一个Writer将模板和数据进行输出进行输出
try {
t.process(root, out);
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.test.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>