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使用技巧。