springboot默认不支持jsp,所以我们使用freemarker模块来实现view(视图层),
根据java开发的原则。从底层开始所以
第一步。设计entity
package com.gxuwz.freemarker.entity;
public class User {
private String userId;
private String userName;
private String sex;
public User(){
}
public User(String userId, String userName, String sex){
this.userId = userId;
this.userName = userName;
this.sex = sex;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
第二部。编写controller类
package com.gxuwz.freemarker.controller;
import com.gxuwz.freemarker.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@Controller
public class StudentController {
@RequestMapping("/freemarker")
public String freemarker(Map<String, Object> map){
User user_one = new User("001","周小狄","男");
User user_two = new User("002","周日月","男");
map.put("name", "Joe");
map.put("sex", 1); //sex:性别,1:男;0:女;
// 模拟数据
List<User> friends = new ArrayList<User>();
friends.add(user_one);
friends.add(user_two);
map.put("friends", friends);
return "freemarker";
}
}
第三步。视图层这里后缀为.html与后缀为.ftl效果一样。文件路径: templates/freemarker.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<center>
<p>
welcome ${name} to freemarker!
</p>
<p>性别:
<#if sex==0>
女
<#elseif sex==1>
男
<#else>
保密
</#if>
</p>
<h4>我的好友:</h4>
<#list friends as item>
姓名:${item.name} , 年龄${item.age}
<br>
</#list>
</center>
</body>
</html>
第四步。设置全局配置application.perporties
server.port=8080
spring.freemarker.allow-request-override=false
spring.freemarker.cache=true
spring.freemarker.check-template-location=true
spring.freemarker.charset=UTF-8
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.suffix=.html
spring.freemarker.templateEncoding=UTF-8
spring.freemarker.templateLoaderPath=classpath:/templates/
spring.freemarker.expose-spring-macro-helpers=false
第五步。
使用freemarker模板要添加依赖(jar)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>