Maven 整合FreeMarker使用
pom.xml
1 <!-- freemarker jar --> 2 <dependency> 3 <groupId>org.freemarker</groupId> 4 <artifactId>freemarker</artifactId> 5 <version>2.3.20</version> 6 </dependency>
testFreeMarker.flt
1 您好${name},现在在测试FreeMarker功能
FreeMarkerUtil.java
1 package pers.kangxu.test.util; 2 3 import java.io.IOException; 4 import java.io.StringWriter; 5 import java.util.Map; 6 7 import javax.servlet.http.HttpServletRequest; 8 9 import freemarker.template.Configuration; 10 import freemarker.template.Template; 11 import freemarker.template.TemplateException; 12 13 /** 14 * 15 * <b> 16 * FreeMarkerUtil 17 * </b> 18 * @author kangxu 19 * 20 */ 21 public class FreeMarkerUtil { 22 23 private static FreeMarkerUtil instance; 24 private Configuration config; 25 26 String templatePath = "/freeMarker/"; 27 28 /** 29 * instance FreeMarkerUtil 30 * @return 31 */ 32 public static FreeMarkerUtil instance() { 33 if (instance == null) { 34 instance = new FreeMarkerUtil(); 35 } 36 return instance; 37 } 38 39 /** 40 * instance Configuration 41 * @param request 42 */ 43 private void configInstance(HttpServletRequest request) { 44 if (this.config == null) { 45 this.config = new Configuration(); 46 this.config.setServletContextForTemplateLoading(request.getSession().getServletContext(),templatePath); 47 } 48 } 49 50 /** 51 * 通过模板文件生成字符串 52 * @param request 53 * @param templateFileName 54 * @param propMap 55 * @return 56 */ 57 public String geneFileStr(HttpServletRequest request,String templateFileName, Map<String, Object> propMap) { 58 configInstance(request); 59 StringWriter out = new StringWriter(); 60 Template tmp; 61 try { 62 tmp = this.config.getTemplate(templateFileName,"UTF-8"); 63 tmp.setEncoding("UTF-8"); 64 tmp.process(propMap, out); 65 } catch (IOException e) { 66 e.printStackTrace(); 67 } catch (TemplateException e) { 68 e.printStackTrace(); 69 } 70 return out.getBuffer().toString(); 71 } 72 73 }
TestController.java
1 package pers.kangxu.test.controller; 2 3 import java.util.HashMap; 4 import java.util.Map; 5 6 import javax.servlet.http.HttpServletRequest; 7 8 import org.springframework.stereotype.Controller; 9 import org.springframework.web.bind.annotation.RequestMapping; 10 import org.springframework.web.bind.annotation.ResponseBody; 11 12 import pers.kangxu.test.util.FreeMarkerUtil; 13 14 15 @Controller 16 @RequestMapping("/test-default") 17 public class TestController { 18 19 @RequestMapping(value="test-freemarker",produces = "application/json; charset=utf-8") 20 @ResponseBody 21 public String testFreeMarker(HttpServletRequest request){ 22 23 Map<String,Object> map = new HashMap<String,Object>(); 24 map.put("name", "【我是名字】"); 25 26 return FreeMarkerUtil.instance().geneFileStr(request, "testFreeMarker.flt", map); 27 } 28 }
运行结果