很轻的,Servlet + Freemarker 组合体,没有那么硬~(转)   Leave a comment

老调重弹。对SSH经典组合有些腻,不再那么轻,重返到若干年前的原始。

Servlet的轻巧高效,Freemarker的强大简便,两者结合将是超轻的组合,即可避免丑陋的Java代码和HTML代码杂揉,又可高效基于模板的站点开发。

闲话少说,项目需要:

freemarker-2.3.13.jar

servlet.jar

定义两个Servlet:

HelloAction.java 对应 /hello,借助Freemarker硬编码输出

 

  1. public class HelloAction extends HttpServlet {  
  2.     private static final long serialVersionUID = -6082007726831320176L;  
  3.   
  4.     private Configuration configuration;  
  5.     public void init() throws ServletException {  
  6.         configuration = new Configuration();  
  7.         configuration.setServletContextForTemplateLoading(getServletContext(), "WEB-INF/pages");  
  8.         configuration.setEncoding(Locale.CHINA, "UTF-8");  
  9.     }  
  10.   
  11.     @SuppressWarnings("unchecked")  
  12.     public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  13.         // 填充数据类型  
  14.         Map map = new HashMap();  
  15.         map.put("userName""小敏");     
  16.         Template template = configuration.getTemplate("hello.html");  
  17.         response.setContentType("text/html; charset=" + template.getEncoding());  
  18.         Writer out = response.getWriter();  
  19.         try{  
  20.             template.process(map, out);  
  21.         }catch (TemplateException e) {  
  22.             e.printStackTrace();  
  23.         }  
  24.     }  
  25.   
  26.     public void destroy() {  
  27.         super.destroy();  
  28.         if(configuration != null){  
  29.             configuration = null;  
  30.         }  
  31.     }  
  32. }  
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;
        }
    }
}

 

对应模板:

  1. <html>  
  2. <head>  
  3. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  4. <title>使用Freemarker渲染2</title>  
  5. </head>  
  6. <body>  
  7. 你好, ${userName!} !  
  8. </body>  
  9. </html>   
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>使用Freemarker渲染2</title>
</head>
<body>
你好, ${userName!} !
</body>
</html> 

 

 

HiAction.java 对应 /hi ,借助Freemrker
Servlet的拦截功能,如以往写代码方式,感觉不到Freemarker的存在。

  1. public class HiAction extends HttpServlet {  
  2.     private static final long serialVersionUID = 518767483952153077L;  
  3.   
  4.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  5.             throws ServletException, IOException {  
  6.   
  7.         request.setAttribute("thename""小敏");  
  8.         request.getRequestDispatcher("/WEB-INF/pages/hi.html").forward(request, response);  
  9.     }  
  10. }  
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);
    }
}

 

对应的模板:

  1. <html>  
  2. <head>  
  3. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  4. <title>使用Freemarker渲染</title>  
  5. </head>  
  6. <body>  
  7. hi ${thename!}~<br />  
  8. </body>  
  9. </html>  
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>使用Freemarker渲染</title>
</head>
<body>
hi ${thename!}~<br />
</body>
</html>

 

 

但需要在web.xml 配置文件中定义如下:

  1. <servlet>  
  2.     <servlet-name>freemarker</servlet-name>  
  3.     <servlet-class>  
  4.         freemarker.ext.servlet.FreemarkerServlet  
  5.     </servlet-class>  
  6.   
  7.     <!– FreemarkerServlet settings: –>  
  8.     <init-param>  
  9.         <param-name>TemplatePath</param-name>  
  10.         <param-value>/</param-value>  
  11.     </init-param>  
  12.     <init-param>  
  13.         <param-name>NoCache</param-name>  
  14.         <param-value>true</param-value>  
  15.     </init-param>  
  16.     <init-param>  
  17.         <param-name>ContentType</param-name>  
  18.         <param-value>text/html; charset=UTF-8</param-value>  
  19.         <!– Forces UTF-8 output encoding! –>  
  20.     </init-param>  
  21.   
  22.     <!– FreeMarker settings: –>  
  23.     <init-param>  
  24.         <param-name>template_update_delay</param-name>  
  25.         <param-value>0</param-value><!– 0 is for development only! Use higher value otherwise. –>  
  26.     </init-param>  
  27.     <init-param>  
  28.         <param-name>default_encoding</param-name>  
  29.         <param-value>UTF-8</param-value><!– The encoding of the template files. –>  
  30.     </init-param>  
  31.     <init-param>  
  32.         <param-name>number_format</param-name>  
  33.         <param-value>0.##########</param-value>  
  34.     </init-param>  
  35.   
  36.     <load-on-startup>1</load-on-startup>  
  37. </servlet>  
  38.   
  39. <servlet-mapping>  
  40.     <servlet-name>freemarker</servlet-name>  
  41.     <url-pattern>*.html</url-pattern>  
  42. </servlet-mapping>  
<servlet>
    <servlet-name>freemarker</servlet-name>
    <servlet-class>
        freemarker.ext.servlet.FreemarkerServlet
    </servlet-class>

    <!-- FreemarkerServlet settings: -->
    <init-param>
        <param-name>TemplatePath</param-name>
        <param-value>/</param-value>
    </init-param>
    <init-param>
        <param-name>NoCache</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>ContentType</param-name>
        <param-value>text/html; charset=UTF-8</param-value>
        <!-- Forces UTF-8 output encoding! -->
    </init-param>

    <!-- FreeMarker settings: -->
    <init-param>
        <param-name>template_update_delay</param-name>
        <param-value>0</param-value><!-- 0 is for development only! Use higher value otherwise. -->
    </init-param>
    <init-param>
        <param-name>default_encoding</param-name>
        <param-value>UTF-8</param-value><!-- The encoding of the template files. -->
    </init-param>
    <init-param>
        <param-name>number_format</param-name>
        <param-value>0.##########</param-value>
    </init-param>

    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>freemarker</servlet-name>
    <url-pattern>*.html</url-pattern>
</servlet-mapping>

 

使用哪一种组合方式,看您喜好了。

借助于Freemarker自身的Servlet工具,只是用于拦截Servlet中forward转向使用到的HTML资源文件。

很简陋,但凑合着能看。

Posted 2009年11月19日 by gw8310 in 未分类

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

%d 博主赞过: