VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > Java教程 >
  • java入门之SpringBoot 集成FreeMarker

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>

相关教程