zoukankan      html  css  js  c++  java
  • Freemarker与Servlet

    1.导入jar包(freemarker.jar)

    2.web.xml配置一个普通servlet

    <servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>example.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello</url-pattern>
    </servlet-mapping>

    3.建立一个模板文件WEB-INF/templates/test.ftl

    <html>
    <head>
    <title>FreeMarker Example Web Application</title>
    </head>
    <body>
    <h3 style="color:red">${message}</h3>
    </body>
    </html>

    4.Servlet控制器HelloServlet.java

    package example;
    
    import java.util.*;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import freemarker.template.*;
    
    /**
    * This Servlet does not do anything useful, just prints "Hello World!". The
    * intent is to help you to get started if you want to build your own Controller
    * servlet that uses FreeMarker for the View. For more advanced example, see the
    * 2nd Web application example.
    */
    public class HelloServlet extends HttpServlet {
    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();
    root.put("message", "测试Hello World!");
    
    // 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);
    }
    }
    }
  • 相关阅读:
    比较器 Comparable 与compartor 的区别及理解
    事务特性、事务隔离级别、spring事务传播特性
    分布式文件上传-FastDFS
    spring-cloud 组件总结以及搭建图示 (六)
    springCloud zuul网关(五)
    hashCode与equals 通过面试题一窥究竟
    【原】那年30岁
    【原】Hyper-V虚拟机设置外部网络访问
    【原】win10 .net framework 3.5安装
    【原】做梦有感
  • 原文地址:https://www.cnblogs.com/wwzyy/p/5497108.html
Copyright © 2011-2022 走看看