上一篇写了构建Maven多模块项目+SSM框架整合(一),基本框架已经搭建好,访问Controller也能测试通过,现在编写前端页面,在传统的Javaweb项目中,大家习惯使用jsp作为前端视图显示,但是jsp依赖于servlet容器,不利于调试,前后端分离不是很好。若不用jsp,我们是否还有其他的选择,答案是肯定的。HTML加载速度会比jsp快,但是又不能使用JSTL的标签库。现在介绍一种模板引擎可解决问题,Thymeleaf.
Java生态圈广泛,自然有很多视图框架,除了JSP之外,还有Freemarker、Velocity、Thymeleaf等很多框架。Thymeleaf的优点是它是基于HTML的,即使视图没有渲染成功,也是一个标准的HTML页面。因此它的可读性很不错,也可以作为设计原型来使用。而且它是完全独立于Java EE容器的,意味着我们可以在任何需要渲染HTML的地方使用Thymeleaf。
Thymeleaf也提供了Spring的支持,我们可以非常方便的在Spring配置文件中声明Thymeleaf Beans,然后用它们渲染视图。
1. 配置Thymeleaf视图解析器
要在Spring中使用Thymeleaf,我们需要配置三个启用Thymeleaf与Spring集成的bean:
- ThymeleafViewResolver:将逻辑视图名称解析为Thymeleaf模板视图;
- SpringTemplateEngine:处理模板并渲染结果;
- TemplateResolver:加载Thymeleaf模板。
在SSM项目中引入Thymeleaf
pom.xml文件中添加需要的依赖
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>3.0.9.RELEASE</version>
</dependency>
配置web.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<!-- Spring IOC配置
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param> -->
<!-- 以下3项参数与log4j的配置相关 -->
<context-param>