Spring boot项目中异常拦截设计和处理详解

2025-05-29 0 46

最近项目用到了spring boot ,但是在控制器返回html视图并渲染参数的时候,存在了疑问。后面考虑用thymeleaf ,感觉真的不错,下面分享给大家

总共四步:

  1. jar 引入
  2. 控制器参数传递
  3. html标签引入
  4. thymeleaf 缓存设置

一、相关jar的引用

1、maven的引用方式:

?

1

2

3

4
<dependency>

<groupid>org.springframework.boot</groupid>

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

</dependency>

2、我现在的项目是用的gradle,在build.gradle 里面的dependency加入以下配置:

?

1
compile "org.springframework.boot:spring-boot-starter-thymeleaf"

二、spring boot 控制器controller的配置,需要使用model来进行参数传递(或者自定义map)

?

1

2

3

4

5

6
@requestmapping("/index")

public string index(model model) {

model.addattribute("loginname", "admin");

model.addattribute("loginid", "27");

return "index";

}

因为thymeleaf 默认的视图返回路径是/src/java/resources/templates ,而且默认后缀是.html , 所以我们的页面视图就放到templates目录下

三、页面视图的配置

1、在html标签上引入thymeleaf 的标签库,然后参数输出就可以直接使用${} 了

?

1

2
<html xmlns="http://www.w3.org/1999/xhtml"

xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">

例如:

?

1

2

3

4

5

6

7

8

9

10

11

12
<!doctype html>

<html xmlns="http://www.w3.org/1999/xhtml"

xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8"></meta>

<title>im test page</title>

</head>

<body>

loginid:<span th:text="${loginid}"></span>

loginname:<span th:text="${loginname}"></span>

</body>

</html>

最后的输出结果:

Spring boot项目中异常拦截设计和处理详解

四、thymeleaf 的缓存配置

每次更改页面,如果不配置thymeleaf 缓存设置为false,那么每次更改html页面都需要重启页面才刷新,这肯定是我们不愿意的

那么有一个简单的办法,在我们的的基础配置文件里面加入一句配置。 例如我的是application.properties 里面加入一句:

?

1

2
#thymeleaf cache set

spring.thymeleaf.cache=false

重启,配置完成

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对快网idc的支持。如果你想了解更多相关内容请查看下面相关链接

原文链接:http://www.cnblogs.com/f-anything/p/10082637.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Spring boot项目中异常拦截设计和处理详解 https://www.kuaiidc.com/110645.html

相关文章

发表评论
暂无评论