template.process(root, out)的用法(shiro项目中来的九)

时间:2022-11-26 17:51:43
 Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
             Template template = getTemplate(ftlName, ftlPath);
             template.process(root, out);
     public static Template getTemplate(String ftlName, String ftlPath) throws Exception{
         try {
             Configuration cfg = new Configuration();                                                  //通过Freemaker的Configuration读取相应的ftl
             cfg.setEncoding(Locale.CHINA, "utf-8");
             cfg.setDirectoryForTemplateLoading(new File(PathUtil.getClassResources()+"/ftl/"+ftlPath));        //设定去哪里读取相应的ftl模板文件
             Template temp = cfg.getTemplate(ftlName);                                                //在模板文件目录中找到名称为name的文件
             return temp;
         } catch (IOException e) {
             e.printStackTrace();
         }
         return null;
     }
template 就是获取的模板
 package com.fh.controller.${packageName}.${objectNameLower};

 import java.io.PrintWriter;
 import java.text.DateFormat;
 import java.text.SimpleDateFormat;
 import java.util.ArrayList;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import javax.annotation.Resource;
 import org.springframework.beans.propertyeditors.CustomDateEditor;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.WebDataBinder;
 import org.springframework.web.bind.annotation.InitBinder;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.ResponseBody;
 import org.springframework.web.servlet.ModelAndView;
 import com.fh.controller.base.BaseController;
 import com.fh.entity.Page;
 import com.fh.util.AppUtil;
 import com.fh.util.ObjectExcelView;
 import com.fh.util.PageData;
 import com.fh.util.Jurisdiction;
 import com.fh.util.Tools;
 import com.fh.service.${packageName}.${objectNameLower}.${objectName}Manager;

 /**
  * 说明:${TITLE}
  * 创建人:FH Q313596790
  * 创建时间:${nowDate?string("yyyy-MM-dd")}
  */
 @Controller
 @RequestMapping(value="/${objectNameLower}")
 public class ${objectName}Controller extends BaseController {

     String menuUrl = "${objectNameLower}/list.do"; //菜单地址(权限用)
     @Resource(name="${objectNameLower}Service")
     private ${objectName}Manager ${objectNameLower}Service;

     /**保存
      * @param
      * @throws Exception
      */
     @RequestMapping(value="/save")
     public ModelAndView save() throws Exception{
         logBefore(logger, Jurisdiction.getUsername()+"新增${objectName}");
         if(!Jurisdiction.buttonJurisdiction(menuUrl, "add")){return null;} //校验权限
         ModelAndView mv = this.getModelAndView();
         PageData pd = new PageData();
         pd = this.getPageData();
         pd.put("${objectNameUpper}_ID", this.get32UUID());    //主键
 <#list fieldList as var><#if var[3] == "否"><#if var[1] == "Date">        pd.put("${var[0]}", Tools.date2Str(new Date()));    //${var[2]}
 <#elseif var[1] == "Integer">        pd.put("${var[0]}", "${var[4]?replace("无",0)}");    //${var[2]}
 <#elseif var[1] == "Double">        pd.put("${var[0]}", "${var[4]?replace("无",0)}");    //${var[2]}
 <#else>        pd.put("${var[0]}", "${var[4]?replace("无","")}");    //${var[2]}
 </#if></#if></#list>        ${objectNameLower}Service.save(pd);
         mv.addObject("msg","success");
         mv.setViewName("save_result");
         return mv;
     }

     /**删除
      * @param out
      * @throws Exception
      */
     @RequestMapping(value="/delete")
     public void delete(PrintWriter out) throws Exception{
         logBefore(logger, Jurisdiction.getUsername()+"删除${objectName}");
         if(!Jurisdiction.buttonJurisdiction(menuUrl, "del")){return;} //校验权限
         PageData pd = new PageData();
         pd = this.getPageData();
         ${objectNameLower}Service.delete(pd);
         out.write("success");
         out.close();
     }

     /**修改
      * @param
      * @throws Exception
      */
     @RequestMapping(value="/edit")
     public ModelAndView edit() throws Exception{
         logBefore(logger, Jurisdiction.getUsername()+"修改${objectName}");
         if(!Jurisdiction.buttonJurisdiction(menuUrl, "edit")){return null;} //校验权限
         ModelAndView mv = this.getModelAndView();
         PageData pd = new PageData();
         pd = this.getPageData();
         ${objectNameLower}Service.edit(pd);
         mv.addObject("msg","success");
         mv.setViewName("save_result");
         return mv;
     }

     /**列表
      * @param page
      * @throws Exception
      */
     @RequestMapping(value="/list")
     public ModelAndView list(Page page) throws Exception{
         logBefore(logger, Jurisdiction.getUsername()+"列表${objectName}");
         //if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;} //校验权限(无权查看时页面会有提示,如果不注释掉这句代码就无法进入列表页面,所以根据情况是否加入本句代码)
         ModelAndView mv = this.getModelAndView();
         PageData pd = new PageData();
         pd = this.getPageData();
         String keywords = pd.getString("keywords");                //关键词检索条件
         if(null != keywords && !"".equals(keywords)){
             pd.put("keywords", keywords.trim());
         }
         page.setPd(pd);
         List<PageData>    varList = ${objectNameLower}Service.list(page);    //列出${objectName}列表
         mv.setViewName("${packageName}/${objectNameLower}/${objectNameLower}_list");
         mv.addObject("varList", varList);
         mv.addObject("pd", pd);
         mv.addObject("QX",Jurisdiction.getHC());    //按钮权限
         return mv;
     }

     /**去新增页面
      * @param
      * @throws Exception
      */
     @RequestMapping(value="/goAdd")
     public ModelAndView goAdd()throws Exception{
         ModelAndView mv = this.getModelAndView();
         PageData pd = new PageData();
         pd = this.getPageData();
         mv.setViewName("${packageName}/${objectNameLower}/${objectNameLower}_edit");
         mv.addObject("msg", "save");
         mv.addObject("pd", pd);
         return mv;
     }    

      /**去修改页面
      * @param
      * @throws Exception
      */
     @RequestMapping(value="/goEdit")
     public ModelAndView goEdit()throws Exception{
         ModelAndView mv = this.getModelAndView();
         PageData pd = new PageData();
         pd = this.getPageData();
         pd = ${objectNameLower}Service.findById(pd);    //根据ID读取
         mv.setViewName("${packageName}/${objectNameLower}/${objectNameLower}_edit");
         mv.addObject("msg", "edit");
         mv.addObject("pd", pd);
         return mv;
     }    

      /**批量删除
      * @param
      * @throws Exception
      */
     @RequestMapping(value="/deleteAll")
     @ResponseBody
     public Object deleteAll() throws Exception{
         logBefore(logger, Jurisdiction.getUsername()+"批量删除${objectName}");
         if(!Jurisdiction.buttonJurisdiction(menuUrl, "del")){return null;} //校验权限
         PageData pd = new PageData();
         Map<String,Object> map = new HashMap<String,Object>();
         pd = this.getPageData();
         List<PageData> pdList = new ArrayList<PageData>();
         String DATA_IDS = pd.getString("DATA_IDS");
         if(null != DATA_IDS && !"".equals(DATA_IDS)){
             String ArrayDATA_IDS[] = DATA_IDS.split(",");
             ${objectNameLower}Service.deleteAll(ArrayDATA_IDS);
             pd.put("msg", "ok");
         }else{
             pd.put("msg", "no");
         }
         pdList.add(pd);
         map.put("list", pdList);
         return AppUtil.returnObject(pd, map);
     }

      /**导出到excel
      * @param
      * @throws Exception
      */
     @RequestMapping(value="/excel")
     public ModelAndView exportExcel() throws Exception{
         logBefore(logger, Jurisdiction.getUsername()+"导出${objectName}到excel");
         if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;}
         ModelAndView mv = new ModelAndView();
         PageData pd = new PageData();
         pd = this.getPageData();
         Map<String,Object> dataMap = new HashMap<String,Object>();
         List<String> titles = new ArrayList<String>();
 <#list fieldList as var>        titles.add("${var[2]}");    //${var_index + 1}
 </#list>        dataMap.put("titles", titles);
         List<PageData> varOList = ${objectNameLower}Service.listAll(pd);
         List<PageData> varList = new ArrayList<PageData>();
         for(int i=0;i<varOList.size();i++){
             PageData vpd = new PageData();
 <#list fieldList as var><#if var[1] == "Integer">            vpd.put("var${var_index + 1}", varOList.get(i).get("${var[0]}").toString());    //${var_index + 1}
 <#elseif var[1] == "Double">            vpd.put("var${var_index + 1}", varOList.get(i).get("${var[0]}").toString());    //${var_index + 1}
 <#else>            vpd.put("var${var_index + 1}", varOList.get(i).getString("${var[0]}"));        //${var_index + 1}
 </#if></#list>            varList.add(vpd);
         }
         dataMap.put("varList", varList);
         ObjectExcelView erv = new ObjectExcelView();
         mv = new ModelAndView(erv,dataMap);
         return mv;
     }

     @InitBinder
     public void initBinder(WebDataBinder binder){
         DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
         binder.registerCustomEditor(Date.class, new CustomDateEditor(format,true));
     }
 }

 null
 null
 {}
 null

root的值

{faobject=, packageName=system, fieldList=[[Ljava.lang.String;@55fbf1af, [Ljava.lang.String;@fb84443, [Ljava.lang.String;@a8992c5, [Ljava.lang.String;@4e02c8ea, [Ljava.lang.String;@18d4a2a9, [Ljava.lang.String;@300311fb], objectName=UserPhoto, nowDate=Fri Feb 09 21:25:26 CST 2018, tabletop=SYS_, objectNameUpper=USERPHOTO, objectNameLower=userphoto, TITLE=用户头像}

只不过这时候获取的模板是动态的,这时候通过

template.process(root, out);

这个方法中root 是动态的这时候root就会动态的把tempate获取的动态数据给替换掉