使用模板和数据模型 动态生成资源 只能在并发小的情况实现
对于大并发的使用环境 需要使用 模板和数据模型 提前生成好静态的html资源 用户访问的时候 直接访问静态html资源即可
生成方法:
@Testpublic void testHtml01() throws IOException, TemplateException {// 1.创建配置类信息Configuration configuration = new Configuration(Configuration.getVersion());// 2.对配置类进行配置String path = this.getClass().getResource("/templates/").getPath();configuration.setDirectoryForTemplateLoading(new File(path));configuration.setDefaultEncoding("utf-8");// 3.获得模板文件对象Template template = configuration.getTemplate("index.ftl");// 4.获得数据模型Map data = getData();// 5.静态化操作String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, data);InputStream inputStream = IOUtils.toInputStream(content);FileOutputStream outputStream = new FileOutputStream(new File("d:/index.html"));IOUtils.copy(inputStream, outputStream);}
生成数据模型map
private Map getData() {Map<String, Object> map = new HashMap<>();Student student = new Student();student.setName("小明");student.setAge(18);//1.纯文本形式的参数map.put("name", "freemarker");//2.实体类相关的参数map.put("stu1", student);//2.1 小强对象模型数据Student stu1 = new Student();// stu1.setName("小强");stu1.setAge(18);stu1.setMoney(1000.86f);stu1.setBirthday(new Date());//2.2 小红对象模型数据Student stu2 = new Student();stu2.setName("小红");stu2.setMoney(200.1f);stu2.setAge(19);//2.3 将两个对象模型数据存放到List集合中List<Student> stus = new ArrayList<>();stus.add(stu1);stus.add(stu2);//2.4 向map中存放List集合数据map.put("stus", stus);//3. 创建Map数据HashMap<String, Student> stuMap = new HashMap<>();stuMap.put("stu1", stu1);stuMap.put("stu2", stu2);// 3.1 向map中存放Map数据map.put("stuMap", stuMap);HashMap<String, Student> stuMapTest = new HashMap<>();stuMapTest.put("stu.name", stu1);map.put("stuMapTest", stuMapTest);//返回Mapreturn map;}
