一般springboot應(yīng)用主要為前端提供數(shù)據(jù)接口,但是對(duì)于一個(gè)小型應(yīng)用來(lái)說(shuō),還需要部署一個(gè)nginx來(lái)承擔(dān)前端應(yīng)用部署的工作闽瓢,這給系統(tǒng)的維護(hù)帶來(lái)了復(fù)雜度。對(duì)于一個(gè)簡(jiǎn)單的應(yīng)用心赶,我們通常希望將前端和后端一同部署到一個(gè)JEE WEB容器中扣讼。springboot應(yīng)用也支持將前后端應(yīng)用部署到一個(gè)WEB容器中,只是springboot不再推薦JSP作為模板語(yǔ)言缨叫,因此我們需要引入新的模板引擎freemarker椭符。
1荔燎、在pom.xml中添加依賴
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
</dependencies>
2、在application.yml文件中配置freemarker
spring:
freemarker:
cache: false
charset: UTF-8
allow-request-override: false
check-template-location: true
#類型
content-type: text/html
expose-request-attributes: true
expose-session-attributes: true
#文件后綴
suffix: .ftl
#路徑
template-loader-path: classpath:/templates/
3销钝、在src/main/resources/templates目錄下創(chuàng)建hello.ftl文件有咨,內(nèi)容如下:
<!DOCTYPE html>
<html lang="cn">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>${userInfo.name}</div>
<div>${userInfo.address}</div>
</body>
</html>
4、創(chuàng)建ctroller:
package com.peng.self.demo.hellodemo.web;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/")
public class HelloPageCtrler {
@GetMapping("/")
public String toHelloPage(ModelMap modelMap) {
Map<String, String> map = new HashMap<>();
map.put("name", "中文姓名");
map.put("address", "看看中文地址是否正常");
modelMap.addAttribute("userInfo", map);
return "hello";//freemarker模板文件路徑(沒(méi)有文件路徑蒸健,默認(rèn)src/main/resources/templates目錄)
}
}
5座享、驗(yàn)證
打開(kāi)瀏覽器,訪問(wèn):http://localhost:8081/似忧,如下如圖所示的頁(yè)面渣叛,說(shuō)明freemarker引入成功:
頁(yè)面結(jié)果
6、引入jQuery靜態(tài)資源
在目錄src/main/resources/static/js目錄下保存jquery-3.6.1.min.js文件盯捌,之后在hello.ftl文件中添加<script>標(biāo)簽引入靜態(tài)資源淳衙,最后添加jQuery頁(yè)面加載執(zhí)行函數(shù)。修改后的hello.ftl文件內(nèi)容如下:
<!DOCTYPE html>
<html lang="cn">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<#-- 引入靜態(tài)js文件 -->
<script src="/js/jquery-3.6.1.min.js"></script>
</head>
<body>
<div>${userInfo.name}</div>
<div>${userInfo.address}</div>
</body>
<script type="text/javascript">
<#-- 頁(yè)面加載后自動(dòng)運(yùn)行 -->
$(function() {
alert("jQuery is OOOOK!")
});
</script>
</html>
再次打開(kāi)瀏覽器訪問(wèn)http://localhost:8081/挽唉,頁(yè)面刷新后瀏覽器彈出警告對(duì)話框滤祖,證明在ftl文件中引入靜態(tài)資源文件成功。