1. 程式人生 > >idea 使用spring boot 搭建freemarker模板

idea 使用spring boot 搭建freemarker模板

省略建立springboot專案的步驟

配置pox.xml新增freemarker依賴

        <!--freemarker模板引擎-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-freemarker</artifactId>
		</dependency>

等待依賴載入完畢

在application.yml加入freemaker相關配置  

server:
    port: 8080
    servlet:
      context-path: /springboot-web
spring:
#FREEMARKER (FreeMarkerAutoConfiguration)
  freemarker:
    allow-request-override: false
#Enable template caching.啟用模板快取。
    cache: false
    check-template-location: true
    charset: UTF-8
    content-type: text/html
    expose-request-attributes: false
    expose-session-attributes: false
    expose-spring-macro-helpers: false
#spring.freemarker.prefix=
#spring.freemarker.request-context-attribute=
#spring.freemarker.settings.*=
#設定面板字尾
    suffix: .ftl
#spring.freemarker.template-loader-path=classpath:/templates/ #comma-separated list
#spring.freemarker.view-names= # whitelist of view names that can be resolved


建立freemarker頁面userInfo.ftl當然也可用直接用html,以ftl為字尾是為了區分其他模板語言

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
${name}
${id}
</body>
</html>

編寫FreemakerController

@Controller
@RequestMapping("/freemaker")
public class FreemakerController {
    @RequestMapping("/showuser.html")
    public ModelAndView showUsername(String id){
        ModelAndView mv = new ModelAndView();
        mv.addObject("id",id);
        mv.addObject("name","dongguo");
        mv.setViewName("/userInfo");
        return  mv;
    }
}

訪問頁面

http://localhost:8080/springboot-web/freemaker/showuser.html?id=123