SpringMvc工程中引入freemarker.jar包,公司項目非maven項目 因此引入jar包
代碼如下
servicelmpl.java
public String createWord(HttpServletRequest request,String fileName,String templateName,Map<String.Object> beanParams){
Configuration configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
try{
//獲取上下文路徑
String classRoot = RequestContext.class.getResource("/").getFile();
String root = new File(classRoot).getParentFile().getParentFile().getCanonicalPath();
String uploadPath = root + File.separator + "template";//上傳文件存放路徑
configuration.setDirectoryForTemplateLoading(new File(uploadPath));
Template t = configuration.getTemplate(templateName);//文件名
String outFilePath = uploadPath + File.separator + fileName;
File file = new File(outFilePath);
FileOutputStream fos = new FileOutputStream(file);
Writer out = new BufferedWriter(new OutputStreamWrite(fos,"utf-8"),10240);
try{
t.process(beamParams,out);
}catch(TemplateException e){
e.printStackTrace();
}
}catch(IOException e){
e.printStackTrace();
}
return fileName;
}
Controller.java
@ResponseBody
@RequestMapping("createPool")
public AjaxResponse createPool(HttpServletRequest request,String name){
String templateName = "emergytest.ftl";
String fileName = "test.doc";
Map<String,Object> beanParams = new HashMap<String,Object>();
beamParams.put("bg1","bgtest");
List<Map<String,Object>> ulist = new ArrayList<Map<String,Object>>();
List<Map<String,Object>> jkejMap = apiService.getGroupList();
Map<String,Object> map = new HashMap<String,Object>();
map.out("jkyj","接口一級");
Map<String,Object> map2 = new HashMap<String,Object>();
map2.put("jkej","接口二級");
jkejMap.add(map2);
map.put("jkejMap",jkejMap);
ulist.add(map);
beanParams.put("uulist",ulist);
String outName = versionService.createPool(request,fileName,templateName,beanParams);
String message = "template" + File.separator + outName;
return new AjaxResponse(true,message,"");
}
js
$('#pool').ajaxSubmit({
url:"pm/version/createPool",
success:function(res){
if(window.ActiveXObject || "ActiveXObject" in window || window.navigator.userAgent.indexOf("Edge") != -1){
window.location.href = $('base').attr('href') + res.message.replace(/\\/g,'/');
}else{
window.location.href = res.message.replace(/\\/g,'/');
}
}
})
ftl文件具體語法
//定義Map接口
<#assign testMap = {"0":"HTTP","1":"HTTPS"}>
<#list uulist as item>
<![CDATA[${item.jkyj}]]>
<#if item.bb == '1'>
<#list item.jkerMap as item2>
<![CDATA[${item2.jkej}]]>