package com;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
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 FreeMarkerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private Configuration cfg;
public void init() {
// Initialize the FreeMarker configuration;
// - Create a configuration instance
cfg = new Configuration();
// - Templates are stoted in the WEB-INF/templates directory of the Web
// app.
cfg.setServletContextForTemplateLoading(getServletContext(),
"WEB-INF/templates");
// In a real-world application various other settings should be
// explicitly
// set here, but for the sake of brevity we leave it out now. See the
// "webapp2" example for them.
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// Build the data-model
Map root = new HashMap();
List bookList = new ArrayList();
Book book = new Book();
book.setBookName("Struts2 基于WebWork核心的MVC开发");
book.setPrice(new Float("98"));
book.setAuthor("李刚");
book.setUrl("http://www.baidu.com");
Book myBook = new Book();
myBook.setBookName("Spring2.0");
myBook.setAuthor("李刚");
myBook.setPrice(new Float("50.5"));
myBook.setUrl("http://www.google.com");
bookList.add(book);
bookList.add(myBook);
root.put("bookList", bookList);
// book.setAuthor("author");
// Get the templat object
Template t = cfg.getTemplate("test.ftl");
// Prepare the HTTP response:
// - Use the charset of template for the output
// - Use text/html MIME-type
resp.setContentType("text/html; charset=" + t.getEncoding());
Writer out = resp.getWriter();
// Merge the data-model and the template
try {
t.process(root, out);
} catch (TemplateException e) {
throw new ServletException(
"Error while processing FreeMarker template", e);
}
}
}
评论0