Thymeleaf与Spring学习笔记

ModelAttribute

在与Spring的集成中,在html页面中基于thymeleaf语法,直接访问model中的属性信息。
在Controller中定义ModelAttribute信息:

@ModelAttribute('allTypes')
public List<Type> populateTypes() {
    return Arrays.asList(Type.ALL);
}

Form使用

创建一个form的代码示例

<form action="#" th:action="@{/seedstartermng}" th:object="${seedStarter}" method="post">
    ...
</form>

这里的th:object就是指在controller中直接访问的model对象。
th:field用于声明属性的值以及name/id的信息。
示例如下:

<input type="text" th:field="*{datePlanted}" />

等价于输出如下信息:

<input type="text" id="datePlanted" name="datePlanted" th:value="*{datePlanted}" />

checkbox的使用示例:

<div>
  <label th:for="${#ids.next('covered')}" th:text="#{seedstarter.covered}">Covered</label>
  <input type="checkbox" th:field="*{covered}" />
</div>

th:for主要是用于绑定对应的input button,这里是covered。ids.next/previous用于找到对应的组件id。

错误信息的展示

一般常用的方式有如下, 在input下面输出错误信息,或者直接修改input的css 风格。
示例如下:

<input type="text" th:field="*{datePlanted}" 
        th:class="${#fields.hasErrors('datePlanted')}? fieldError" />

在当前的input中,修改css的风格,用以显示错误信息。
第二种方式的示例:

<input type="text" th:field="*{datePlanted}" />
<p th:if="${#fields.hasErrors('datePlanted')}" th:errors="*{datePlanted}">Incorrect date</p>

基于

节点来承载错误信息的展示。

直接访问spring的Bean

在thymeleaf中允许直接访问spring中的Bean,示例如下:

div th:text="${@urlService.getApplicationUrl()}">...</div> 

urlService表示spring中管理的Bean Name。

Spring Security集成

其中常用的Tag如下:

<div sec:authorize="isAuthenticated()">
  This content is only shown to authenticated users.
</div>
<div sec:authorize="hasRole('ROLE_ADMIN')">
  This content is only shown to administrators.
</div>
<div sec:authorize="hasRole('ROLE_USER')">
  This content is only shown to users.
</div>

Logged user: <span sec:authentication="name">Bob</span>
Roles: <span sec:authentication="principal.authorities">[ROLE_USER, ROLE_ADMIN]</span>

上述例子中,展示了具体的Tag使用技巧。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值