Java使用servlet+freemarker渲染html视图

创建web project

编写配置类

package com.mazun.weixin.freemarker;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import freemarker.template.Configuration;
import freemarker.template.Template;

public class FreemarkerViewRender {

	public static void respondView(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 1创建Freemarker配置实例并设置模版文件位置
		Configuration cfg = new Configuration();
		// cfg.setDirectoryForTemplateLoading(new File("src/main/webapp/tpl"));
		cfg.setServletContextForTemplateLoading(request.getServletContext(), "templets");

		// 2创建数据模型
		Map root = new HashMap();
		Map supplier = new HashMap();
		//supplier.put("info", new Supplier());此处简化如下

		supplier.put("pName", "Render");
		supplier.put("pId", "No1003484432");
		supplier.put("sName", "FreeMarker");

		root.put("data", supplier);

		// 3加载模板文件
		Template temp = cfg.getTemplate("index.html");

		// 4显示生成的数据
		// Writer out = new OutputStreamWriter(System.out);
		response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		temp.process(root, out);
		out.flush();
	}
}

编写service()

package com.mazun.weixin.service;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mazun.weixin.freemarker.FreemarkerViewRender;

@WebServlet(urlPatterns = "/showInfo", name = "Render")
public class Render extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			try {
				FreemarkerViewRender.respondView(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.doGet(req, resp);
	}
}

创建Floder命名templets

创建File命名index.html





freemarker渲染


	
<#list data?values as proInfo> ${proInfo}
部署项目在浏览器输入http://localhost:8080/WeChat/showInfo即可


你可能感兴趣的:(Java使用servlet+freemarker渲染html视图)