自己瞎捉摸学习:十三种设计模式之模板方式设计

 模板方式就是将对象分为可变与不可变得部分,就例如spring_mvc中的共有行为和特有行为,将不可变的部分封装起来,提供给需要此类对象操作的用户,然后将再有用户对对可变部分进行自己的进一步处理,就例如springmvc中的特有行为.

目前已用的模板设计模式,

1,JDBCtemplate

  顾名思义,在操作数据库连接池对数据库进行CRUD时,其中的某些步骤的固定不定的,例如注册驱动,获取连接对象等,而JDBCTemplate就是对这些共性进行了封装 我们使用时只需创建此类对象,然后对对象进行可变行为的操作,例如按照不同的需要撰写不同的sql语句,然后再通过JDBC模板获得查询对象

2,Freemarker

  用Java语言写的模板工具,可以用来生成静态页面,对于用户经常访问的页面可以设置为静态页面,减少数据库的访问量,生成时机,当第一次查询数据库时生成

  环境搭建,

     在逻辑层创建属性文件freemarker.properties

out_put_path=D:/ideaProjects/health_parent/health_mobile/src/main/webapp/pages         // 此路径为生成静态页面的路径

    在spring配置文件中配置

        <property name="templateLoaderPath" value="/WEB-INF/ftl/" />
          <!--指定字符集-->
          <property name="defaultEncoding" value="UTF-8" />
          </bean>
        <context:property-placeholder location="classpath:freemarker.properties"/>

  在需要生成页面的类中创建路径对象并进行注入

  @Value("${out_put_path}")//从属性文件读取输出目录的路径
  private String outputpath ;

  创建静态页面模板生成方法

  public void generateHtml(String templateName,String htmlPageName,Map<String, Object> dataMap){//三个参数分别为 模板名,生成的静态页面名,注入数据
    Configuration configuration = freeMarkerConfigurer.getConfiguration();
    Writer out = null;
    try {
      // 加载模版文件
      Template template = configuration.getTemplate(templateName);
      // 生成数据
      File docFile = new File(outputpath + "\\" + htmlPageName);
      out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
      // 输出文件
      template.process(dataMap, out);
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (null != out) {
          out.flush();
        }
      } catch (Exception e2) {
        e2.printStackTrace();
      }
    }
  }
}

   创建静态页面生成方法  

  //生成静态页面
  public void generateMobileStaticHtml() {
    //准备模板中需要注入的数据,调取本类中的其他方法获取
    List<Setmeal> setmealList = this.findAll();
    //生成单个静态页面方法
    generateMobileSetmealListHtml(setmealList);
    //生成对个静态页面方法
    generateMobileSetmealDetailHtml(setmealList);
  }

  生成单个静态页面方法

  public void generateMobileSetmealListHtml(List<Setmeal> setmealList) { //参数列表为注入数据,由于是单个,里面只有一个页面的所需数据
    Map<String, Object> dataMap = new HashMap<String, Object>();
    dataMap.put("setmealList", setmealList);//将数据存入模板所需的map中
    this.generateHtml("mobile_setmeal.ftl","m_setmeal.html",dataMap);//调用本类中的模板方法
  }

  生成多个静态页面方法

  

  public void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
    for (Setmeal setmeal : setmealList) { //由于是多个数据,所以需要遍历
      Map<String, Object> dataMap = new HashMap<String, Object>();
      dataMap.put("setmeal", this.findById(setmeal.getId()));
      this.generateHtml("mobile_setmeal_detail.ftl",
                        "setmeal_detail_"+setmeal.getId()+".html",
                        dataMap);
    }
  }

  最后在需要生成静态页面的方法中调用静态页面生成方法 generateMobileStaticHtm 即可

3 JasperReports

  对IText的一个封装 itext  java中生成pdf模板的工具

  使用步骤

  在指定文件夹内倒入.jrxml的模板文件

  

public Result exportBusinessReport4PDF(HttpServletRequest request, HttpServletResponse response) {
    try {
        Map<String, Object> result = reportService.getBusinessReportData();
​
        //取出返回结果数据,准备将报表数据写入到PDF文件中
        List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");
​
        //动态获取模板文件绝对磁盘路径
        String jrxmlPath = 
            request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jrxml";//此路径为模板文件路径
        String jasperPath = 
            request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jasper";//此路径为模板文件生成的二进制值文件
        //编译模板
        JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);
​
        //填充数据---使用JavaBean数据源方式填充
        JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath,result,new JRBeanCollectionDataSource(hotSetmeal));
        ServletOutputStream out = response.getOutputStream();
        response.setContentType("application/pdf");//确定输出文件格式
        response.setHeader("content-Disposition", "attachment;filename=report.pdf");
        //输出文件
        JasperExportManager.exportReportToPdfStream(jasperPrint,out);
        return null;
    } catch (Exception e) {
        e.printStackTrace();
        return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
    }
}

  JasperReport工作原理

    

     ,存在一个模板文件本质是一个xml文件

    对其进行编译得到一个二进制的后缀名为jasper的文件,用于代码填充数据

    Jrprint 填充数据后得到的对象,等待输出

    Expoet对象进行输出,可以指定输出的报表为何种格式

    最终获得一个输出了的相应格式文件

.

猜你喜欢

转载自www.cnblogs.com/jumpTk/p/12173596.html
今日推荐