前言
昨晚筆者將之前的項目改造成使用springboot框架,在前端頁面上使用shiro標籤的時候遇到了thymeleaf模板中的js腳本里使用shiro標籤不起作用
這個問題。
由於頁面表格使用的是bootstrapTable,列表中的按鈕是在js中動態生成的,而列表中的按鈕是受權限控制。
先看看原本在jsp中的使用(以下代碼只選取涉及到的):
var operator = {
title: "操作",
field: "",
formatter: function (value, row, index) {
var buttonHtml = '';
<shiro:hasPermission name="user:update">
buttonHtml += '<a href="javascript:void(0);" id="edit_' + index + '" uniqueId="' + row.userId + '"><span class="glyphicon glyphicon-pencil" title="修改"></span></a> ';
</shiro:hasPermission>
<shiro:hasPermission name="user:del">
buttonHtml += '<a href="javascript:void(0);" id="del_' + index + '" uniqueId="' + row.userId + '"><span class="glyphicon glyphicon-trash" title="刪除"></span></a>';
</shiro:hasPermission>
return buttonHtml;
}
};
如果在thymeleaf模板中也如上的寫法的話,則頁面會報錯。至於爲何無法解析模板中的js腳本里的權限標籤這裏筆者沒有深入查找原因。
注:如何在thymeleaf中使用shiro標籤,讀者可自行網上搜索,這裏不重複說明
問題解決方式
由於shiro標籤可以直接在模板中(不是在模板中的js裏面)直接使用,那麼筆者實現的 思路如下:
- 在模板html中定義一個div,裏面包含shiro權限判斷
- shiro權限判斷完成後,那麼頁面中剩下的就是用戶該有的權限
- 通過js/jquery來獲取這個div中的按鈕,然後再bootstrapTable在加載每行的時候來獲取這個div中的按鈕,再進行相應的操作(如對按鈕的id等屬性進行賦值)即可
實現方式:
- 定義一個div#operateDiv,然後加入shiro權限判斷
<table class="table table-striped table-hover" id="dataTables-example">
</table>
<div id="operateDiv" style="display: none;">
<shiro:hasPermission name="user:update">
<a href="javascript:void(0);" id="edit_" uniqueId=""><span class="glyphicon glyphicon-pencil" title="修改"></span></a>
</shiro:hasPermission>
<shiro:hasPermission name="user:del">
<a href="javascript:void(0);" id="del_" uniqueId=""><span class="glyphicon glyphicon-trash" title="刪除"></span></a>
</shiro:hasPermission>
</div>
- 在模板中的js裏
require(['../js/sys/user'], function (user) {
//定義一個獲取按鈕的方法
function getOperateBtns(index, id) {
var html = "";
$("#operateDiv").find("a").each(function(){
var _srcid = $(this).attr("id");
var _id = _srcid + index;
var _uniqueId = id;
$(this).attr("id", _id);//筆者對按鈕的id屬性進行賦值
$(this).attr("uniqueId", _uniqueId);//筆者對按鈕的uniqueId屬性進行賦值
html += this.outerHTML + " ";
$(this).attr("id", _srcid);
});
return html;
}
//按鈕列
var operator = {
title: "操作",
field: "",
formatter: function (value, row, index) {
return getOperateBtns(index, row.userId);
}
};
//其他代碼這忽略(如使用bootstrapTable初始化表格等,這裏可在其他js文件中實現即可,不一定要模板中的js腳本里實現)...
//....
//對修改按鈕綁定事件
$("#dataTables-example").on("click", "[id^='edit_']", function () {
var uniqueId = $(this).attr("uniqueId");
user.update(uniqueId);
});
//對刪除按鈕綁定事件
$("#dataTables-example").on("click", "[id^='del_']", function () {
var uniqueId = $(this).attr("uniqueId");
user.del(uniqueId);
});
});
以上爲筆者解決該問題的主要代碼