(三)Spring Boot 视图层技术

一、整合 Thymeleaf

       Thyme leaf 是新一代 Java 模板引擎,类似于 Velocity、 FreeMarker 等传统 Java 模板引擎。与传统Java 模板引擎不同的是 Thymeleaf 支持 HTML 原型,既可以让前端工程师在浏览器中直接打开查看样式, 也可以让后端工程师结合真实数据查看显示效果。 同时,Spring Boot 提供了 Thymeleaf 自动化配置解决方案,因此在 Spring Boot 中使用 Thymeleaf 非常方便。 Spring Boot 整合 Thymeleaf 主要可通过如下步骤:

1.1 创建工程,添加依赖

新建 Spring Boot 工程,然后添加 spring-boot-starter-web 和 spring-boot-starter-thymeleaf 依赖,代码如下:

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

1.2 配置 Thymeleaf

Spring Boot 为 Thymleaf 提供了自动化配置类 ThymeleafAutoConfiguration ,相关的配置属性在ThymleafPropertie 类中, ThymleafProperti 部分源码如下:

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {

	private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;

	public static final String DEFAULT_PREFIX = "classpath:/templates/";

	public static final String DEFAULT_SUFFIX = ".html";

  //省略.....  
}

由此配置可以看到,默认的模板位置在 classpath:/templates/,默认的模板后缀为 .html 如果使用IntlliJ IDEA 工具创建 Spring Boot 项目,templates 文件夹默认就会创建。
当然,如果开发者想对默认的 Thymeleaf 配置参数进行自定义配置,那么可以直接在application.propertie 中进行配置,部分常见配置如下:
分源码如下:

# 是否开启缓存,开发时可设置为 false ,默认为 true
spring.thymeleaf.cache=true
# 检查模板是否存在,默认为 true
spring.thymeleaf.check-template=true
#检查模板位置是否存在,默认为 true
spring.thymeleaf.check-template-location=true
# 模板文件编码
spring.thymeleaf.encoding=utf-8
# 模板文件位置
spring.thymeleaf.prefix=classpath:/templates/
#Content Type 配置
spring.thymeleaf.servlet.content-type=text/html
# 模板文件后缀
spring.thymeleaf.suffix=.html

1.3 配置控制器

创建 Book 实体类,然后在 Controller 中返回 ModelAndView ,代码如下:

public class Book {
    private Integer id;
    private String name;
    protected String author;
    //省略get/set方法
}

@RestController
public class BookController {
    @GetMapping("/books")
    public ModelAndView books() {
        List<Book> books = new ArrayList<>();
        Book bl = new Book();
        bl.setId(1);
        bl.setAuthor("罗贯中");
        bl.setName("三国演义");
        Book b2 = new Book();
        b2.setId(2);
        b2.setAuthor("曹雪芹");
        b2.setName("红楼梦");
        books.add(bl);
        books.add(b2);
        ModelAndView mv = new ModelAndView();
        mv.addObject("books", books);
        mv.setViewName("books");
        return mv;
    }
}

1.4 创建视图

在resources 目录下的 templates 录中创建 books.html 具体代码如下

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" >
<head>
<meta charset="UTF-8">
<title>图书列表</title>
</head>
<body>
<table border="1">
<tr>
    <td>图书编号</td>
    <td>图书名称</td>
    <td>图书作者</td>
</tr>
<tr th:each="book:${books }" >
 <td th:text="${ book.id }" ></td>
 <td th:text="${ book.name }" ></td>
 <td th:text = "${ book.author }"></td>
</tr>

</table>
</body>
</html>

1.5 运行

在浏览器地址栏中输入“http://localhost:8080/books”, 即可看到运行结果。

二、整合 FreeMarker

       FreeMarker 是一个非常古老的模板引擎,可以用 Web 环境或者非 Web 境中。与 Thymeleaf 不同 FreeMarker 需要经过解析才能够在浏览器中展示出来。 FreeMarker 不仅可以用来配置 HTML页面模板,也可以作为电子邮件模板、配置文件模板以及源码模板等。 Spring Boot 中对 FreeMarker 整合提供了很好的支持,主要整合步骤如下:

2.1 创建项目 ,添加依赖

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

2.2 配置 FreeMarker

Spring Boot 对 FreeMarker 也提供了自动化配置类 FreeMarkerAutoConfiguration,相关的配置属性在 FreeMarkerProperties 中,FreeMarkerProperties 部分源码如下:

@ConfigurationProperties(prefix = "spring.freemarker")
public class FreeMarkerProperties extends AbstractTemplateViewResolverProperties {
    public static final String DEFAULT_TEMPLATE_LOADER_PATH = "classpath:/templates/";
    public static final String DEFAULT_PREFIX = "";
    public static final String DEFAULT_SUFFIX = ".ftlh";
    private Map<String, String> settings = new HashMap();
    private String[] templateLoaderPath = new String[]{"classpath:/templates/"};
    private boolean preferFileSystemAccess;

    public FreeMarkerProperties() {
        super("", ".ftlh");
    }
    //........
}

从该默认配置中可以看到, FreeMarker 默认模板位置和 Thymeleaf 一样 ,都在classpath:/templates 中, 默认文件后缀是.ftlh。开发者可以在 application.properties 中对这些默认配置进行修改,部分常见配置如下:

# HttpServletRequest 的属性是否可以覆盖 controller i:p model 的同名项
spring.freemarker.allow-request-override=false
# HttpSession 的属性是否可以覆盖 controller中model 的同名项
spring.freemarker.allow-session-override=false
# 是否开启缓存
spring.freemarker.cache=false
# 模板文件编码
spring.freemarker.charset=UTF-8
# 是否检查模板位置
spring.freemarker.check-template-location=true
#Content Type 的值
spring.freemarker.content-type=text/html
# 是否将 HttpServletRequest 中的属性添加到 Model 中
spring.freemarker.expose-request-attributes=false
# 是否将 HttpSession 中的属性添加到 Model
spring.freemarker.expose-session-attributes=false
# 模板文件后缀
spring.freemarker.suffix=.ftl
# 模板文件位置
spring.freemarker.template-loader-path=classpath:/templates/

2.3 配置控制器

创建 Book 实体类,然后在 Controller 中返回 ModelAndView ,代码如下:

public class Book {
    private Integer id;
    private String name;
    protected String author;
    //省略get/set方法
}

@RestController
public class BookController {
    @GetMapping("/books")
    public ModelAndView books() {
        List<Book> books = new ArrayList<>();
        Book bl = new Book();
        bl.setId(1);
        bl.setAuthor("罗贯中");
        bl.setName("三国演义");
        Book b2 = new Book();
        b2.setId(2);
        b2.setAuthor("曹雪芹");
        b2.setName("红楼梦");
        books.add(bl);
        books.add(b2);
        ModelAndView mv = new ModelAndView();
        mv.addObject("books", books);
        mv.setViewName("books");
        return mv;
    }
}

2.4 创建视图

按照配置文件,在 resources/templates 目录下创建 books.ftl 文件, 内容如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图书列表</title>
</head>
<body>
<table border="1">
    <tr>
        <td>图书编号</td>
        <td>图书名称</td>
        <td>图书作者</td>
    </tr>
    <#if books ??&&(books?size>O)>
        <#list books as book>
            <tr>
                <td>${book.id}</td>
                <td>${book.nam}</td>
                <td>${book.author}</td>
            </tr>
        </#list>
    </#if>
</table>
</body>
</html>

2.5 运行

在浏览器地址栏中输入“http://localhost:8080/books”, 即可看到运行结果。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值