备忘录《六》thymeleaf 使用学习总结、避免再次踩坑

本文总结了在Spring Boot2项目中使用Thymeleaf遇到的问题,特别是关于th:onclick动态传参的限制及其解决方案,以及th:include、th:replace的区别和th:each的使用案例。在th:onclick中,只能传入numbers或booleans,可通过data-*属性传递复杂对象。同时,介绍了th:include用于内容替换,th:replace用于标签替换,th:each用于遍历,并给出了分页逻辑的示例。最后提到了th:src与内置对象的使用。
摘要由CSDN通过智能技术生成

       最近使用Spring boot2+thymeleaf做了一个项目,由于第一次使用thymeleaf,所有遇到很多坑,不过更多坑是其他人写的博客,最让我无语的是,是我搜索如何在onclick里传对象,基本没有一个说对的,最坑的是,明明thymeleaf不允许在th:onclick中传String类型,他们写的博客都是传int的,他们自以为这个就是正确的传参,好吧,无语。真的博客十有八九都有小问题。

下面列举出,我在项目中使用到的标签,在此这里记录一下,以作整理与分享。

1.th:onclick(注意,onclick动态传参时,只能传入numbers or booleans 类型,不然会报错:Only variable expressions returning numbers or booleans are allowed in this context, any other datatypes are not trusted in the context of this expression, including Strings or any other object that could be rendered as a text literal. A typical case is HTML attributes for event handlers (e.g. "onload"), in which textual data from variables should better be output to "data-*" attributes and then read from the event handler. )文档写的很清楚了,其他类型可以通过data-*传递,实际项目中,其实我们一般都是传对象到JS,虽然thymeleaf有直接传对象到JS的,但是很局限,不符合实际要求,下面说一下我的做法。

首先我在返回的model中重写toString方法,把该model对象提前转成了json

@Override
public String toString() {
      /*返回的字符串当中不能包含富文本,不然前端赋值给某个属性时会报错*/
       return publicUtil.replaceBlank(JSONObject.fromObject(this).toString());
}

/**
* publicUtil工具类,去除字符串空格
 * @param str
 * @return
 */
public static String replaceBlank(String str) {
	String dest = "";
	if (str!=null) {
		Pattern p = Pattern.compile("\\s*|\t|\r|\n");
		Matcher m = p.matcher(str);
		dest = m.replaceAll("");
	}
	return dest;
}

html页面引用时,通过data-*传递

<a href="javascript:void(0)"  th:attr="data-account=${cloudCollection.toString()}"  onclick="toLookCloudDetail(this,'1')"> 
<img th:src="${#httpServletRequest.getContextPath()}+'/images/see.png'" data-toggle="tooltip" data-placement="bottom" title="查看详情"></a>

重点查看th:attr="data-account=${cloudCollection.toString()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值