刚新开的一个项目用到了SpringBoot和FreeMark,对freeMark没有用过,没办法,只能边学边做了。今天周五,晚上约了朋友开黑,想想有点小激动......
引入pom文件:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
我是在构建SpringBoot的时候直接添加的FreeMark,搭建SpringBoot项目传送门
application.properties配置文件:
# FREEMARKER (FreeMarkerAutoConfiguration)
spring.freemarker.allow-request-override=false
spring.freemarker.allow-session-override=false
spring.freemarker.cache=false
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.enabled=true
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.expose-spring-macro-helpers=true
spring.freemarker.prefer-file-system-access=true
# 过滤.ftl 后缀的文件
spring.freemarker.suffix=.ftl
# spring boot 默认的页面模板的存放目录
spring.freemarker.template-loader-path=classpath:/templates/
spring.freemarker.settings.template_update_delay=0
spring.freemarker.settings.default_encoding=UTF-8
spring.freemarker.settings.classic_compatible=true
spring.freemarker.order=1
src/main/resources 目录 templates下, 创建 login.ftl
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<meta http-equiv= "Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
欢迎你:${myname} <br/>
Hello Word !
<h1>${name} </h1>
<h1 style="color: red">${profession} </h1>
<h1>${student.stuName }</h1>
<h1> ${time?string("yyyy-MM-dd HH:mm:ss") }</h1>
</body>
</html>
编写Controller:
Student 是我建 一个实体
package com.cn.restyle.controller;
import java.util.Date;
import java.util.Map;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.cn.restyle.entity.Student;
@Controller
@RequestMapping("v1")
public class LoginController {
@RequestMapping("demo")
public String demo(Map<String, Object> map,Model model){
map.put("myname", "zhangxusheng");
Student student = new Student();
student.setAge(23);
student.setCreateTime(new Date());
student.setStuName("Lisa");
model.addAttribute(student);
model.addAttribute("name", "zhangsan");
model.addAttribute("profession", "codeMonkey");
model.addAttribute("time", new Date());
return "login";
}
}
运行SpringBoot的启动类application,然后访问: localhost:8080/v1/demo
TIM图片20171208134146.png