pom.xml
<!-- freemarker jar -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.20</version>
</dependency>
testFreeMarker.flt
您好${name},现在在测试FreeMarker功能
FreeMarkerUtil.java
package pers.kangxu.test.util; import java.io.IOException;
import java.io.StringWriter;
import java.util.Map; import javax.servlet.http.HttpServletRequest; import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException; /**
*
* <b>
* FreeMarkerUtil
* </b>
* @author kangxu
*
*/
public class FreeMarkerUtil { private static FreeMarkerUtil instance;
private Configuration config; String templatePath = "/freeMarker/"; /**
* instance FreeMarkerUtil
* @return
*/
public static FreeMarkerUtil instance() {
if (instance == null) {
instance = new FreeMarkerUtil();
}
return instance;
} /**
* instance Configuration
* @param request
*/
private void configInstance(HttpServletRequest request) {
if (this.config == null) {
this.config = new Configuration();
this.config.setServletContextForTemplateLoading(request.getSession().getServletContext(),templatePath);
}
} /**
* 通过模板文件生成字符串
* @param request
* @param templateFileName
* @param propMap
* @return
*/
public String geneFileStr(HttpServletRequest request,String templateFileName, Map<String, Object> propMap) {
configInstance(request);
StringWriter out = new StringWriter();
Template tmp;
try {
tmp = this.config.getTemplate(templateFileName,"UTF-8");
tmp.setEncoding("UTF-8");
tmp.process(propMap, out);
} catch (IOException e) {
e.printStackTrace();
} catch (TemplateException e) {
e.printStackTrace();
}
return out.getBuffer().toString();
} }
TestController.java
package pers.kangxu.test.controller; import java.util.HashMap;
import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody; import pers.kangxu.test.util.FreeMarkerUtil; @Controller
@RequestMapping("/test-default")
public class TestController { @RequestMapping(value="test-freemarker",produces = "application/json; charset=utf-8")
@ResponseBody
public String testFreeMarker(HttpServletRequest request){ Map<String,Object> map = new HashMap<String,Object>();
map.put("name", "【我是名字】"); return FreeMarkerUtil.instance().geneFileStr(request, "testFreeMarker.flt", map);
}
}
运行结果