慕课网_《Java模板引擎之Freemarker》学习总结

时间:2017年3月19日星期日
说明:本文部分内容均来自慕课网。@慕课网:http://www.imooc.com
教学示例源码:无
个人学习源码:https://github.com/zccodere/s...

第一章:快速入门

1-1 Java模版引擎freemarker简介

本节要点

什么是Freemarker
数据模型+模版=输出(HTML)
前端设计师和程序员的学习侧重点

什么是Freemarker

Freemarker是一款模版引擎
Freemarker不是web框架
官网:http:// freemarker.org

Freemarker原理

clipboard.png

前端设计师和程序员的学习侧重点

MVC设计(Model、View、Controller)
前端设计师侧重于View(模版设计)
程序员全面掌握MVC

如何开始?
一点心得

先划一个范围
再定一个目标
创建可行计划
边玩边学

1-2 maven构建freemarker项目

本节要点

Maven构建Spring+Freemarker项目
配置文件介绍
运行小例:列表展示

Maven构建Spring+Freemarker项目

Eclipse+Maven使用简介
Maven依赖Spring和Freemarker的jar包
Spring配置文件和Freemarker Servlet配置文件

配置文件介绍

Spring配置文件applicationContext.xml
Spring Freemarker Servlet配置文件spring-servlet.xml

1-3 maven构建freemarker项目代码实战

我学习时,使用springboot来进行项目搭建,同时,项目基于javaconfig进行配置。
整体目录结构如下:

clipboard.png

项目POM文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.zccoder</groupId>
  <artifactId>myfreemarker</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        
        <!-- 用于数据持久化 -->
        <!-- <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency> -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.28</version>
</dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
  
  
</project>

配置Freemarker

package com.myimooc.myfreemarker.config;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.springframework.web.servlet.view.freemarker.FreeMarkerView;
import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.myimooc.myfreemarker.web.controller.RoleDirectiveModel;

/**
 * Web项目SpringMvc配置
 * @author ZhangCheng
 * @date 2017-03-19
 * @version V1.0
 */
@Configuration
@EnableWebMvc
@ComponentScan("com.myimooc.myfreemarker")
public class SpringMvcConfig extends WebMvcConfigurerAdapter{
    
    /**
     * 配置视图解析器
     * @return
     */
    @Bean
    public FreeMarkerViewResolver getFreeMarkerViewResolver(){
        FreeMarkerViewResolver freeMarkerViewResolver = new FreeMarkerViewResolver();
        
        freeMarkerViewResolver.setOrder(1);
        freeMarkerViewResolver.setSuffix(".html");
        freeMarkerViewResolver.setCache(false);
        freeMarkerViewResolver.setRequestContextAttribute("request");
        freeMarkerViewResolver.setContentType("text/html;charset=utf-8");
        freeMarkerViewResolver.setViewClass(FreeMarkerView.class);
        
        return freeMarkerViewResolver;
    }
    
    /**
     * 配置静态资源映射
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }
    /**
     * 配置FASTJSON
     * @return
     */
    @Bean
    public FastJsonHttpMessageConverter  fastJsonHttpMessageConverters() {
       FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        
       FastJsonConfig fastJsonConfig = new FastJsonConfig();
       fastJsonConfig.setSerializerFeatures(SerializerFeature.QuoteFieldNames);
       fastJsonConfig.setCharset(Charset.forName("UTF-8"));
       fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
       
       List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
       supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
       
       fastConverter.setSupportedMediaTypes(supportedMediaTypes);
       fastConverter.setFastJsonConfig(fastJsonConfig);
       return fastConverter;
    }
    
    /**
     * 配置FreeMarker
     * @return
     */
    @Bean
    public FreeMarkerConfigurer getFreeMarkerConfigurer(){
        FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
        freeMarkerConfigurer.setDefaultEncoding("UTF-8");
        freeMarkerConfigurer.setTemplateLoaderPath("classpath:/templates/");
        
        Properties settings = new Properties();
        settings.setProperty("template_update_delay", "5");
        settings.setProperty("url_escaping_charset", "UTF-8");
        settings.setProperty("defaultEncoding", "UTF-8");
        settings.setProperty("whitespace_stripping", "true");
        settings.setProperty("boolean_format", "true,false");
        settings.setProperty("number_format", "0.##########");
        settings.setProperty("locale", "zh_CN");
        settings.setProperty("datetime_format", "yyyy-MM-dd HH:mm:ss");
        settings.setProperty("date_format", "yyyy-MM-dd");
        settings.setProperty("time_format", "HH:mm:ss");
        settings.setProperty("tag_syntax", "square_bracket");
        settings.setProperty("classic_compatible", "true");
        settings.setProperty("template_exception_handler", "ignore");
        settings.setProperty("auto_import", "/spring.ftl as spring, /common/spring.ftl as spring");
        freeMarkerConfigurer.setFreemarkerSettings(settings);
        
        // 配置自定义指令
        Map<String,Object> variables = new HashMap<String,Object>();
        variables.put("role", new RoleDirectiveModel());
        freeMarkerConfigurer.setFreemarkerVariables(variables);
        
        return freeMarkerConfigurer;
    }
    
    /**
     * 配置JSON解析器
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        converters.add(this.fastJsonHttpMessageConverters());
    }
}

配置Web,类似于web.xml

package com.myimooc.myfreemarker.config;

import java.util.EnumSet;

import javax.servlet.DispatcherType;
import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * Web项目启动类
 * 
 * @author ZhangCheng
 * @date 2017-03-19
 * @version V1.0
 *
 */
@Configuration
public class WebConfig implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();

        context.register(SpringMvcConfig.class);

        // 新建WebApplication,注册配置类,并将其和当前servletContext关联。
        context.setServletContext(servletContext);

        // 注册SpringMVC的DispatcherServlet。
        ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(context));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);

        // 注册SpringMVC的字符过滤器
        FilterRegistration.Dynamic encodingFilter = servletContext.addFilter("encoding", new CharacterEncodingFilter());
        EnumSet<DispatcherType> dispatcherTypes = EnumSet.allOf(DispatcherType.class);
        dispatcherTypes.add(DispatcherType.REQUEST);
        dispatcherTypes.add(DispatcherType.FORWARD);
        encodingFilter.addMappingForUrlPatterns(dispatcherTypes, true, "*");
        encodingFilter.setInitParameter("encoding", "UTF-8");

    }

}

新建模版页面

clipboard.png

编写控制器

clipboard.png

启动项目

clipboard.png

1-4 小例子:列表demo展示

clipboard.png

编写控制器

clipboard.png

编写Freemarker

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>${username}</h1>

<ul>
    [#list userList as item]
    <li>${item.name}的生日是:${item.birthday?string('yyyy-MM-dd')}</li>
    [/#list]
</ul>

</body>
</html>

效果如下:

clipboard.png

1-5 补充:springboot集成freemarker

输入网址:start.spring.io

第二章:基础技能

2-1 freemarker取值章节简介

本节要点

Java中常用的数据模型
取值(插值)指令
逻辑指令:if、switch

2-2 Java数据模型、freemarker取值

Java中常用的数据模型

基本类型数据(比如Integer)
封装的对象类型(比如User对象)
集合类型:List、Map

取值指令

常用${var}语法进行取值
对null、不存在对象取值${var!}
取包装对象的值,通过“点”语法:${User.name}
取值的时候进行计算、赋值
Date类型格式${date?string(‘yyyy-MM-dd’)}
如何转义HTML内容:${var?html}

2-3 freemarker取java基本数据模型的值

控制器

clipboard.png

页面层

clipboard.png

效果图

clipboard.png

2-4 boolean类型值的format

布尔值:${booleanVar?string('yes','no')}

2-5 date类型值的format

日期:${dateVar?string('yyyy-MM-dd')}

2-6 null或者不存在的变量取值

null:${nullVar!'我是默认值'}
missing:${ssssVar!'我是默认值'}

第三章:技能进阶

3-1 变量的定义、赋值、运算

编写代码:

<h2>2. 赋值运算</h2>
<ul>
    <li>赋值&运算</li>
    [#assign a = 100 /]
    a = ${a}
    <br/>
    a+100=${a+100}
</ul>

效果如下:

clipboard.png

3-2 自定义对象User变量的取值

clipboard.png

clipboard.png

clipboard.png

3-3 集合List的遍历

语法:

[#list listName as item]
    <font color="red">${item!}</font><br/>
[/#list]

3-4 集合Map的遍历

语法:

[#list map?keys as key]
    <font color="red">${key}:${map[key]!}</font><br/>
[/#list]

3-5 if语法

语法:

    <li>if else</li>
    [#assign var = 100/]
    [#if var == 99]
        <font color="red">var = 99</font><br/>
    [#else]
        <font color="red">var != 99</font><br/>
    [/#if]

判断某个对象或值是否存在

[#if myList?exists]
[/#if]
或
[#if myList??]
[/#if]

3-6 switch语法

语法:

    <li>switch case break default</li>
    [#assign var3 = 10 /]
    [#switch var3]
        
    [#case 10] 10<br/>
        [#break]
    
    [#case 100] 100<br/>
        [#break]
    
    [#default] other
    
    [/#switch]

第四章:高级技巧

4-1 自定义函数章节介绍

本节要点

字符串、集合操作
自定义函数
自定义指令

补充表达式指令

+ :字符串连接,集合连接
[index]:下标取值

自定义函数

自定义排序函数
实现TemplateMethodModelEx接口

自定义指令

实现TemplateDirectiveModel接口

4-2 string基本操作指令

代码:

<h2>6. 字符操作</h2>
<ul>
    <li>字符串常用内建函数-连接</li>
    [#assign stra = 'hello' /]
    [#assign strb = 'world' /]
    <font color="red">${stra + strb}</font><br/>
    
    <li>字符串常用内建函数-截取</li>
    <font color="red">${(stra + strb)?substring(5,8)}</font><br/>
    
    <li>字符串常用内建函数-长度</li>
    <font color="red">${(stra + strb)?length}</font><br/>
    
    <li>字符串常用内建函数-大写</li>
    <font color="red">${(stra + strb)?upper_case}</font><br/>
    
    <li>字符串常用内建函数-小写</li>
    <font color="red">${(stra + strb)?lower_case}</font><br/>
    
    <li>字符串常用内建函数-index_of</li>
    <font color="red">${(stra + strb)?index_of('w')}</font><br/>
    
    <li>字符串常用内建函数-last_index_of</li>
    <font color="red">${(stra + strb)?last_index_of('o')}</font><br/>
    
    <li>字符串常用内建函数-replace</li>
    <font color="red">${(stra + strb)?replace('o','xx')}</font><br/>
</ul>

效果图:

clipboard.png

4-3 自定义函数

步骤一:编写自定义函数类

clipboard.png

步骤二:再返回的控制器里面,添加自定义函数类,并指定方法名

clipboard.png

步骤三:在页面使用排序方法

clipboard.png

步骤四:验证输出

clipboard.png

4-4 list排序内建函数、常用指令

使用内建函数进行排序,item_index为下标,默认为升序

    [#list mylistinfo?sort as item]
            ${item_index}:${item},
    [/#list]

使用内建函数进行排序,降序

    [#list mylistinfo?sort?reverse as item]
        ${item_index}:${item},
    [/#list]

其它常用内建函数

    <li>List长度</li>
    ${mylistinfo?size}
    <li>List下标取值</li>
    ${mylistinfo[3]}

效果图:

clipboard.png

4-5 自定义指令

步骤一:编写自定义指令类

clipboard.png

步骤二:注册自定义指令类

clipboard.png

步骤三:页面使用自定义指令

clipboard.png

步骤四:验证输出

clipboard.png

4-6 freemarker常用内建函数

本节要点

处理字符串内建函数
处理数字的内建函数
处理list的内建函数
其他内建函数

处理字符串内建函数

substring、cap_first、ends_with、contains
date、datetime、time
starts_with、index_of、last_index_of、split、trim

处理数字的内建函数

string、x?string(“0.##”)
round、floor、ceiling

梳理List的内建函数

first、last、seq_contains、seq_index_of
size、reverse、sort、sort_by
chunk

其他内建函数

is函数:is_string、is_number、is_method
()、has_content函数
eval求值

4-7 freemarker内建函数代码讲解

代码示例

clipboard.png

效果图如下:

clipboard.png

4-8 macro、function指令

本节要点

宏macro、nested、return指令
函数function、return指令
课程总结

macro、nested、return

macro语法
[@macro_name param /] 调用macro
nested语法

function、return

function语法
${function_name(param)}调用

macro、nested、return章节
macro语法:

[#macro macro_name param1 param2 param3 paramN]
Trmplate_code ${param1}
    [#nested/]
[/#macro]

调用

[@macro_name param1=”value1” param2=”value2”/]

[@macro_name param1=”value1” param2=”value2”/]
    Nested_template
[@macro_name/]

Function语法:

[#function function_name param1 param2]
    [#return param1 + param2]
[/#function]

调用

${doAdd(100,100)}

代码示例

clipboard.png
clipboard.png

效果如下

clipboard.png

第五章:课程总结

5-1 课程总结

clipboard.png

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值