在 Spring Boot 应用程序中根据用户角色有条件地渲染 DataTables 操作 我的 Spring Boot 应用程序中有一个 DataTables 实现,并且我尝试根据用户的角色有条件地在 DataTable 中呈现操作。 DataTable 包含一个操作列,仅当用户具有 EDITOR 角色时,该操作列才应显示编辑、删除和查看按钮。
这是有条件渲染删除按钮的 Thymeleaf 代码:
<form th:if="${#lists.contains(roles, 'EDITOR')}" style="display:inline !important;" th:action="@{/touchPoint/delete/}" method="post" onsubmit="return confirm('Do you really want to delete this Assignment? This action cannot be reversed.');">
<input type="hidden" name="id" th:value="*{TouchPointID}"/>
<button class="form-command btn btn-danger btn-sm" type="submit"><i class="fa fa-trash-o"></i></button>
</form>
在我的 DataTables 配置中,我在 API 响应中发送用户角色:
// Controller API method
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
List<String> authorityStrings = authorities.stream()
.map(GrantedAuthority::getAuthority)
.collect(Collectors.toList());
response.put("authorities", authorityStrings); // places the authorities in the 'authorities' obj
这是我的 DataTables 配置的相关部分,即操作列:
"columns": [
// ... other columns
{
"data": null,
"render": function (data, type, row) {
var authorities = json.authorities || [];
var hasEditorRole = authorities.includes('EDITOR');
if (hasEditorRole) {
return '<button class="edit-button">Edit</button>';
} else {
return 'No action';
}
}
}
// ... other columns
],
数据表由 javascript (jQuery) 填充,Thymeleaf 与之无关。
如上所述,您可以将html页面中的
authorities
作为json数组加载,并在数据表中构造行时检查权限。
// somewhere in the html
<script th:inline="javascript">
// authorities as a json array
const authorities = /*[[${authorities}]]*/ '';
const deleteUrl = /*[[@{drink/delete}]]*/ ''; // we will use this later
</script>
通常数据表结果集中的行由对象数组表示。如果我们显示“饮料”对象的数组,响应中的数据集很可能类似于:
"data": [
{
"drinkId" : 1,
"name" : "Coca cola"
},
{
"drinkId" : 2,
"name" : "Pepsi"
},
{
"drinkId" : 3,
"name" : "Expresso"
}
]
现在条件渲染纯粹用javascript完成,这里没有thymeleaf。
"columns": [
// ... other columns
{
"data": null,
"render": function (data, type, row) {
var hasDeleteRole = authorities.includes('DELETE');
if (hasDeleteRole) {
// just an example of how to use the delete url and the drinkId which is unique per row
return '<a href="deleteUrl + \'?id=' + row.id + '\'"/>'
// after resolving the above, it should something look like this in the html <a href="http://localhost/delete-drink?id=3"/>
} else {
return 'No action';
}
}
}
// ... other columns
],