Spring Boot 使用 FreeMarker 渲染页面

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lzx_2011/article/details/72810926

Spring Boot提供了默认配置的模板引擎主要有以下几种:

FreeMarker
Groovy
Thymeleaf
Mustache

Spring Boot 建议使用上面这些模板引擎,避免使用 JSP,若一定要使用 JSP 将无法实现 Spring Boot 的多种特性。

导入 freemarker 依赖

在 pom.xml 文件中添加如下依赖。

<!-- Spring Boot Freemarker 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

controller 文件

使用 @Controller 而不是先前的 @RestController (restful api 形式,返回 json)方法返回值是 String 类型,和 Freemarker 文件名一致。这样才会准确地把数据渲染到 ftl 文件里面进行展示。向 Model 加入数据,并指定在该数据在 Freemarker 取值指定的名称,和传统的 jsp 开发类似。

@Controller
@RequestMapping(value = "/user")
public class UserController {

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String getUser(Model model, @PathVariable("id") Long id) {
        User user = new User();
        user.setId(id);
        user.setName("liu");
        user.setAge(20);
        model.addAttribute("user", user);
        return "user";
    }

}

freemarker 文件

新建 user.ftl 文件,放到 resources/templates 目录下。

<!DOCTYPE html>
<html>
<body>
id: ${user.id}
<br>
name: ${user.name}
<br>
age: ${user.age}
</body>
</html>

运行应用

启动 web 应用,执行命令

mvn spring-boot:run

在浏览器上输入 http://localhost:8080/user/1 可以看到返回结果

id: 1 
name: liu 
age: 20

项目示例:https://github.com/lzx2011/springBootPractice

猜你喜欢

转载自blog.csdn.net/lzx_2011/article/details/72810926