简介
FreeMarker是一款模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页、电子邮件、配置文件、源代码等)的通用工具。 它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件
JavaEE中的两种开发方式
前后端不分离
要求程序员要掌握js,为了简化页面开发,引入页面模板,页面模板整体上来说又可以分为两大类
前端模板
前端模板就是后缀为html的模板,代表就是Thymeleaf,这种模板有一个好处就是不需要服务端解析就能直接在浏览器中打开。
后端模板
必须经过服务端解析才能被浏览器展示出来的模板
JSP
Freemarker
velocity
前后端分离
前后端分离的时候,后端纯粹只是接口,没有任何页面。所有的页面由前端完成,前端会使用相关的模板。
Vue
AngularJS
React
HelloWorld案例
创建一个maven项目
整合spring和SpringMVC
引入freemarker
1.引入freemarker依赖
org.freemarker
freemarker
2.3.28
2.创建freemarker变量文件
freemarker-var.properties
3.配置视图解析器
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
expression="org.springframework.stereotype.Controller" />
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
classpath:freemarker-var.properties
class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
10
zh_CN
yyyy-MM-dd HH:mm:ss
yyyy-MM-dd
HH:mm:ss
#.####
class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
value="org.springframework.web.servlet.view.freemarker.FreeMarkerView" />
4.测试
在WEB-INF下创建 index.ftl
controller跳转到index.ftl页面
@Controller
public class UserController {
@RequestMapping("/hello")
public String hello(){
return "index";
}
}
插值规则
通用插值
字符串,数字,Boolean型,Date类型
@RequestMapping("/hello")
public String hello(Model m){
m.addAttribute("name", "张三");
m.addAttribute("age", 18);
m.addAttribute("enable", true);
m.addAttribute("birth",new Date());
return "index";
}
Insert title hereHello Freemarker
${root}
${name}
${age}
${enable?string("true","false")}
${birth?string("yyyy-MM-dd")}
数字格式化插入
数字格式化插值可采用#{expr;format}形式来格式化数字,其中format可以是:
mX:小数部分最小X位
MX:小数部分最大X位
#{x;M2}
#{y;M2}
#{x;m3}
#{y;m3}
eclipse安装Freemarker插件
重启即可