1. 程式人生 > >一頭扎進springboot之使用Freemarker模板引擎渲染web檢視

一頭扎進springboot之使用Freemarker模板引擎渲染web檢視

在springboot的官方文件中是不建議在專案中使用jsp這樣的技術的,取而代之的是freemark、velocity這樣的模板引擎。

首先和大家來說一下這個模板引擎的概念,這裡特指用於web開發的模板引擎。模板引擎是為了使使用者介面與業務資料(內容)分離而產生的,它可以生成特定格式的文件,用於網站的模板引擎就會生成一個標準的HTML文件

那麼我們的freemark也是有著自己凸顯的優點在,才會這麼受歡迎

1.freemark不支援寫java程式碼,實現嚴格的mvc分離

2.效能非常不錯

3.對jsp標籤支援良好

4.內建大量常用功能,使用非常方便

5.巨集定義(類似jsp標籤)非常方便

6.使用表示式語言

然後現在來看怎麼在springboot中整合freemark模板

1》.在pom.xml檔案中引入freemark的依賴包

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2》在src/main/resource/建立一個templates資料夾,字尾為*.ftl,裡面新建一個index.ftl的檔案,內容如下
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title></title>
</head>
<body>
	  ${name}
</body> 
</html>

3》Controller層寫入一個方法,內容如下
@Controller
public class IndexController {

	@RequestMapping("/index")
	public String index(ModelMap map){//ModelMap轉發值的作用
		map.addAttribute("name","喵喵");
		return "index";
	}
}

這樣我們在訪問這個方法時,就能夠獲取到值了


簡單的freemark的整合就是這樣的,然後我們在來看看freemark裡獲取list的資料是怎麼獲取的

先去IndexController造一些list的資料

@Controller
public class IndexController {

	@RequestMapping("/index")
	public String index(ModelMap map){//ModelMap轉發值的作用
		map.addAttribute("name","喵喵");
		map.put("sex", 1);
		List<String> userList = new ArrayList<String>();
		userList.add("張三");
		userList.add("李四");
		userList.add("王五");
		map.addAttribute("userList",userList);
		return "index";
	}
}

然後在index.ftl利用list接受遍歷即可,這裡的寫法和jsp還是有很大的區別的
<#if sex==1>
            男
      <#elseif sex==2>
            女
     <#else>
        其他      
	  
	  </#if>
	  
	 <#list userlist as user>
	   ${user}
	 </#list>

然後我們在訪問方法時,瀏覽器就會顯示我們獲取到的資料啦


如果想要了解freemark更多的內容,可以私信哦