springboot整合常用组件和服务【6】springboot支持freemarker

freemarker是一模板技术,用来代替较重的jsp,本文讲述springboot如何整合freemarker。

1、环境约束

  • win10 64位操作系统
  • idea2018.1.5
  • maven-3.0.5
  • jdk-8u162-windows-x64

2、前提约束

  • 完成springboot创建web项目 https://www.jianshu.com/p/de979f53ad80
    注意:笔者创建项目的时候约束的包前缀是net.wanho.springboot.springbootfreemarkerdemo,读者可以自行创建包名,只是要注意本文中的代码也要修改包名

3、修改pom.xml

在dependencies标签中加入以下依赖:

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

4、在net.wanho.springboot.springbootfreemarkerdemo包下面创建controller、entity子包

在entity下创建User.java

package net.wanho.springboot.springbootfreemarkerdemo.entity;

public class User
{
    private int id;
    private String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public User() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

在controller下面创建UserController.java

package net.wanho.springboot.springbootfreemarkerdemo.controller;

import net.wanho.springboot.springbootfreemarkerdemo.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

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


    @RequestMapping(value = "/show")
    public ModelAndView index(ModelAndView modelAndView) {
        modelAndView.setViewName("index");
        List<User> userList = new ArrayList<>();
        userList.add(new User(1, "zhangli"));
        userList.add(new User(2, "ali"));
        userList.add(new User(3, "xiaoli"));
        modelAndView.addObject("userList", userList);
        return modelAndView;
    }
}

5、在resources/templates下创建index.ftl【注意,依赖的css,js需要读者自行导入】

<!DOCTYPE html>
<html>
<head lang="en">
    <title>Spring Boot Demo - FreeMarker</title>
    <link rel="stylesheet" href="/css/bootstrap.min.3.3.5.css"/>
    <script src="/js/jquery-1.11.2.min.js" type="text/javascript"></script>
    <script src="/js/bootstrap.js" type="text/javascript"></script>
</head>
<body>
    <table class="table">
        <caption>用户基本信息</caption>
        <thead>
        <tr>
            <th>id</th>
            <th>姓名</th>
        </tr>
        </thead>
           <#list userList as user>
            <tr>
                <td>${user.id!}</td>
                <td>${user.name!}</td>
            </tr>
           </#list>
    </table>
</body>
</html>

6、启动测试

在浏览器中输入http://localhost:8080/user/show,查看效果,具体情况如下:

测试


至此,我们完成了springboot支持freemarker,并完成了测试。

猜你喜欢

转载自blog.csdn.net/qq_41717874/article/details/88972576