使用Freemarker模板引擎渲染web視圖
在Web前端的學習中我們會應用多種的模板引擎來快速的完成動態網站的開發,下面就給大家詳細的講解一下使用Freemarker模板引擎渲染web視圖的應用方法。
1.3.1、pom文件引入:
<!-- 引入freeMarker的依賴包. --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> |
1.3.2、后臺代碼
在src/main/resources/創建一個templates文件夾,后綴為*.ftl
??????????? @RequestMapping("/index") ???????? public String index(Map<String, Object> map) { ???????? ??? map.put("name","美麗的天使..."); ???????? ?? return "index"; ???????? } |
1.3.3、前臺代碼
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8" /> <title></title> </head> <body> ??????????? ? ${name} </body> </html> |
1.3.4、Freemarker其他用法
@RequestMapping("/freemarkerIndex") ??????????? public String index(Map<String, Object> result) { ?????????????????????? result.put("name", "zhaocong"); ?????????????????????? result.put("sex", "0"); ?????????????????????? List<String> userlist = new ArrayList<String>(); ?????????????????????? userlist .add("zhangsan"); ?????????????????????? userlist .add("lisi"); ?????????????????????? userlist .add("atguigu"); ?????????????????????? result.put("userlist ", userlist ); ?????????????????????? return "index"; ??????????? }
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8" /> <title>首頁</title> </head> <body> ?????? ? ${name} <#if sex=="1"> ??????????? 男 ????? <#elseif sex=="2"> ??????????? 女 ???? <#else> ??????? 帥氣的boy? ???????? ? </#if>????? ? ???????? ?<#list userlist as user> ???????? ?? ${user} ???????? ?</#list> </body> </html>
|
1.3.5、Freemarker配置
新建application.properties文件
######################################################## ###FREEMARKER (FreeMarkerAutoConfiguration) ######################################################## 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.expose-spring-macro-helpers=false #spring.freemarker.prefix= #spring.freemarker.request-context-attribute= #spring.freemarker.settings.*= spring.freemarker.suffix=.ftl spring.freemarker.template-loader-path=classpath:/templates/ #comma-separated list #spring.freemarker.view-names= # whitelist of view names that can be resolved |