首页 > 编程语言 > 详细

SpringBoot 集成FreeMarker

时间:2020-02-07 20:38:36      阅读:47      评论:0      收藏:0      [点我收藏+]

 

SpringBoot官方不推荐使用jsp,因为jsp不好发挥SpringBoot的特性。官方推荐使用模板引擎代替jsp,现在很多公司都使用FreeMarker来作为SpringBoot的视图。

 

SpringBoot对动态页面的支持很好,为多种模板引擎提供了默认配置,常用的有:

  • Thymeleaf
  • FreeMarker
  • Velocity
  • Groovy

 

 


 

 

SpringBoot集成FreeMarker

(1)在pom.xml中添加依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

 

 

(2)在springboot的配置文件application.proeprties中配置freeamarker

#启用freemark。默认为false——不使用freemarker。
spring.freemarker.enabled=true
#指定freemarker模板文件的后缀
spring.freemarker.suffix=.ftl

这一步是必须的,但很多教程上都没写。

 

 

(3)在controller中转发到freemarker页面,并传递数据

@Controller
public class UserController {

    @RequestMapping("/user")
    public String handler(Model model){
        model.addAttribute("username", "chy");
        return "user/user_info";
    }

}

@RestController用来传回json数据,一般用来写与前端交互的接口。普通的controller用@Controller就行了。

 

 

(4)在reosurces下新建文件夹templates,templates下新建.ftl文件(freemark文件),使用controller传来的数据。

springboot默认模板存放路径是resources\templates,由于user有多个视图,我们在templates下新建文件夹user来存放。

user下新建html文件user_info.html,Shif+F6重命名为.ftl文件。

<body>
<#--取数据-->
${username}
</body>

 

SpringBoot 集成FreeMarker

原文:https://www.cnblogs.com/chy18883701161/p/12274161.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!