freemarker 与 servlet 之 Helloworld版本

新建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 dataModel = new HashMap();
		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:



  freemarker
  
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
  
  
    
    HelloWorldServlet
    HelloWorldServlet
    com.freemaker.servlet.HelloWorldServlet
  
  
    HelloWorldServlet
    /HelloWorldServlet
  

WEB-INF/ftl/helloworld.ftl:




  helloworld

    
      ${username}
    

可以运行。


但是,如果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: ---------- 


你可能感兴趣的:(freemarker)