很轻的,Servlet + Freemarker 组合体,没有那么硬~

老调重弹。对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;
        }
    }
}

对应模板:




使用Freemarker渲染2


你好, ${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);
    }
}

对应的模板:




使用Freemarker渲染


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资源文件。

很简陋,但凑合着能看。

项目源代码已经打包如下:

下载源文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值