springboot+freemarker 開發


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>



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM