dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.3.16.3</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.19</version>
</dependency>
public String toApp(HttpServletRequest request){
String realPath = request.getSession().getServletContext().getRealPath("\\html");File dir = new File(realPath);
if(!dir.exists()){
dir.mkdir();
}
Integer id =Integer.parseInt(request.getParameter("id"));
//System.out.println(id);
App app = as.findAppById(id);
ArrayList<App_pic> imglist = as.findAppImgListById(id);
//System.out.println(imglist);
HashMap<String,Object> map = new HashMap<String,Object>();
map.put("app", app);
map.put("imglist", imglist);
try {
Configuration cfg =new Configuration();
cfg.setClassForTemplateLoading(this.getClass(), "../../"); //这个../../是相对路径 相对于发布在 tomcat 里 appcontrl.clas是 就是编译过的文件 那个位置放的是 生成html的模板
Template template =cfg.getTemplate("appdetail.ftl","utf-8");
FileWriterWithEncoding fileWriterWithEncoding =new FileWriterWithEncoding(new File(realPath+"\\"+app.getId()+".html"), "UTF-8"); //放生成页面的位置 我是放在发布的项目里了 可以访问 就是 webapp下 发布的 appstore项目 可以有 String realPath = request.getSession().getServletContext().getRealPath("\\html"); 这个获得并且是这个目录里的 html文件夹 没有就建一个
template.process(map, fileWriterWithEncoding); //传入 map
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/html/"+id+".html";
}
模板里
map 里的 app信息 可以 直接 ${app.id}来用
<#list imglist as appimg>
<div id="mj_tu_${appimg_index+1}" class="mj_img"> //每个list里的 index 可以 这样表示 appimg_index 从0开始
<img
src="/app${appimg.picurl}" //这是虚拟路径
alt="">
</div>
</#list>
freemaker的基本语法:
<# ... > 中存放所有freemaker的内容,之外的内容全部原样输出。
<@ ... /> 是函数调用
两个定界符内的内容中,第一个符号表示指令或者函数名,其后的跟随参数。freemaker提供的控制包括如下:
<#if condition><#elseif condition><#else></#if> 条件判断
<#list hash_or_seq as var></#list> 遍历hash表或者collection(freemaker称作sequence)的成员
<#macro name param1 param2 ... ><#nested param></#macro> 宏,无返回参数
<#function name param1 param2><#return val></#function> 函数,有返回参数
var?member_function(...) 用函数对var进行转换,freemaker称为build-ins。实际内部实现类似member_function(var, ...)
stringA[M .. N] 取子字符串,类似substring(stringA, M, N)
{key:value, key2:value2 ...} 直接定义一个hash表
[item0, item1, item2 ...] 直接定义一个序列
hash0[key0] 存取hash表中key对应的元素
seq0[5] 存取序列指定下标的元素
<@function1 param0 param1 ... /> 调用函数function1
<@macro0 param0 param1 ; nest_param0 nest_param1 ...> nest_body </@macro> 调用宏,并处理宏的嵌套
<#assign var = value > 定义变量并初始化
<#local var = value> 在 macro 或者 function 中定义局部变量并初始化
<#global var = value > 定义全局变量并初始化
${var} 输出并替换为表达式的值
<#visit xmlnode> 调用macro匹配xmlnode本身及其子节点
<#recurse xmlnode> 调用macro匹配xmlnode的子节点