SpringBoot整合视图层技术

在目前的企业级应用开发中,前后端分离是趋势,但是视图层技术还占有一席之地。Spring Boot对视图层技术提供了很好的支持,官方推荐使用的模板引擎是Thymeleaf,不过像FreeMarker也支持,JSP 技术在这里并不推荐使用。

 

 

Thymeleaf

配置

引入jar包:

<dependency>

      <groupId>org.springframework.boot</groupId>

      <artifactId>spring-boot-starter-thymeleaf</artifactId>

    </dependency>

 

spring boot配置:

#thymeleaf start

spring.thymeleaf.mode=HTML5

spring.thymeleaf.encoding=UTF-8

spring.thymeleaf.content-type=text/html

#开发时关闭缓存,不然没法看到实时页面

spring.thymeleaf.cache=false

#thymeleaf end

 

页面引入:

<html xmlns:th="http://www.thymeleaf.org">

 

 

 

标签的使用

引入url

<a th:href="@{http://blog.csdn.net/u012706811}">绝对路径</a>

<a th:href="@{/}">相对路径</a>

<a th:href="@{css/bootstrap.min.css}">Content路径,默认访问static下的css文件夹</a>

当要写动态链接时括号属性如:@{user(id=${user.id})()..} 相等于 user?id=1&..

 

 

 

th:action

<form id="form" th:action="@{/login}">...</form>

 

th:href

<a th:href="@{/logout}" ></a>

 

th:src

<script th:src="@{/resources/js/jquery/jquery.json-2.4.min.js}"

 

th:text

<td th:text="${username}" ></td>

 

th:value

<option th:value="Adult">Adult</option>
<input type="hidden" th:value="${msg}" />

 

th:include

th:replace

th:fragment

声明定义该属性的div为模板片段,常用与头文件、页尾文件的引入。常与th:include,th:replace一起使用。

例如:

声明模板片段/WEBINF/templates/footer. html 

<div th: fragment=" copy" >
© 2011 The Good Thymes Virtual Grocery
</div>

引入模板片段

<div th: include=" /templates/footer : : copy" ></div>
<div th: replace=" /templates/footer : : copy" ></div>

 

th:if

<div th:if="${rowStat.index} == 0">... do something ...</div>

 

th:each

<form id="login-form" th:action="@{/addStudent}"

th:object="${stuReqBean}" method="POST">

<div class="student" th:each="stuIter,rowStat:${stuReqBean.students}">

<input type="text" class="firstName" value=""

th:field="*{students[__${rowStat.index}__].firstName}"></input>

<input type="text" class="school" value=""

th:field="*{students[__${rowStat.index}__].school}"></input>

...

</div>

</form>

 

上面的例子中通过选择表达式*{}既能将表单绑定到后台的StudentRequestBean中的集合属性students,也能将Servlet上下文中的StudentRequestBean中的List类型的students变量回显,回显时通过th:each进行遍历。

注意1:绑定集合属性元素下标的用法*{students[__${rowStat.index}__].firstName}

注意2:如果List<Student> students为null,页面将无法显示表单,后台必须给students初始化一个值,即:

List<Student > stus = new ArrayList<Student >();

stus .add(new Student ());

StudentRequestBean.setStudents(stus );

注意3:stuIter代表students的迭代器

 

th:object

<form id="login-form" th:action="@{/login}" th:object="${loginBean}">...</form>

 

th:field

<form id="login-form" th:action="@{/login}" th:object="${loginBean}">...
<input type="text" value="" th:field="*{username}"></input>
<input type="text" value="" th:field="*{user[0].username}"></input>
</form>

 

posted on 2019-05-05 15:33  纸菠萝  阅读(431)  评论(0编辑  收藏  举报