老调重弹。对SSH经典组合有些腻,不再那么轻,重返到若干年前的原始。
Servlet的轻巧高效,Freemarker的强大简便,两者结合将是超轻的组合,即可避免丑陋的Java代码和HTML代码杂揉,又可高效基于模板的站点开发。
闲话少说,项目需要:
freemarker-2.3.13.jar
servlet.jar
定义两个Servlet:
HelloAction.java 对应 /hello,借助Freemarker硬编码输出
public class HelloAction extends HttpServlet {
private static final long serialVersionUID = -6082007726831320176L;
private Configuration configuration;
public void init() throws ServletException {
configuration = new Configuration();
configuration.setServletContextForTemplateLoading(getServletContext(), "WEB-INF/pages");
configuration.setEncoding(Locale.CHINA, "UTF-8");
}
@SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 填充数据类型
Map map = new HashMap();
map.put("userName", "小敏");
Template template = configuration.getTemplate("hello.html");
response.setContentType("text/html; charset=" + template.getEncoding());
Writer out = response.getWriter();
try{
template.process(map, out);
}catch (TemplateException e) {
e.printStackTrace();
}
}
public void destroy() {
super.destroy();
if(configuration != null){
configuration = null;
}
}
}
对应模板:
你好, ${userName!} !
HiAction.java 对应 /hi ,借助Freemrker Servlet的拦截功能,如以往写代码方式,感觉不到Freemarker的存在。
public class HiAction extends HttpServlet {
private static final long serialVersionUID = 518767483952153077L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("thename", "小敏");
request.getRequestDispatcher("/WEB-INF/pages/hi.html").forward(request, response);
}
}
对应的模板:
hi ${thename!}~
但需要在web.xml 配置文件中定义如下:
freemarker
freemarker.ext.servlet.FreemarkerServlet
TemplatePath
/
NoCache
true
ContentType
text/html; charset=UTF-8
template_update_delay
0
default_encoding
UTF-8
number_format
0.##########
1
freemarker
*.html
使用哪一种组合方式,看您喜好了。
借助于Freemarker自身的Servlet工具,只是用于拦截Servlet中forward转向使用到的HTML资源文件。
很简陋,但凑合着能看。
项目源代码已经打包如下: