You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot整合DataTables服务端处理时的HTML条件渲染方案

Spring Boot + DataTables服务端模式下基于角色的操作列条件渲染完整实现

一、后端角色信息传递优化

确保角色信息同时支持Thymeleaf页面渲染和DataTables服务端接口返回:

  1. 页面渲染变量传递:在页面跳转Controller方法中,将用户角色存入Model,供Thymeleaf使用:
@GetMapping("/touchpoints")
public String touchPointPage(Model model) {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    List<String> roles = authentication.getAuthorities().stream()
            .map(GrantedAuthority::getAuthority)
            .collect(Collectors.toList());
    model.addAttribute("roles", roles);
    return "touchpoint/list";
}
  1. DataTables服务端接口:保留你现有逻辑,在返回的JSON响应中携带authorities字段,供DataTables渲染时读取。

二、前端Thymeleaf初始化角色变量

在页面JS块中,通过Thymeleaf内联脚本将后端角色信息转为前端可直接使用的变量:

<script th:inline="javascript">
    // 将后端传递的角色列表转为JS数组
    const userRoles = [[${roles}]];
    // 提前判断是否拥有EDITOR角色
    const hasEditorRole = userRoles.includes('EDITOR');
</script>

三、DataTables操作列完整条件渲染逻辑

修改DataTables的columns配置,动态生成编辑、查看、删除按钮(包含完整表单逻辑,注意Spring Boot的CSRF令牌处理):

"columns": [
    // 其他列配置...
    {
        "data": null,
        "render": function (data, type, row) {
            let actionHtml = '';
            
            if (hasEditorRole) {
                // 编辑按钮(可绑定点击事件触发弹窗或跳转)
                actionHtml += `<button class="edit-button btn btn-primary btn-sm" data-id="${row.TouchPointID}">
                                <i class="fa fa-pencil"></i> 编辑
                              </button>&nbsp;`;
                // 查看按钮
                actionHtml += `<button class="view-button btn btn-info btn-sm" data-id="${row.TouchPointID}">
                                <i class="fa fa-eye"></i> 查看
                              </button>&nbsp;`;
                // 删除按钮(包含表单及CSRF令牌)
                actionHtml += `<form style="display:inline !important;" action="/touchPoint/delete/" method="post" 
                                onsubmit="return confirm('确定要删除这条记录吗?此操作不可撤销。')">
                                <input type="hidden" name="id" value="${row.TouchPointID}">
                                <!-- 注入Spring Boot CSRF令牌 -->
                                <input type="hidden" name="_csrf" value="${_csrf.token}">
                                <button class="form-command btn btn-danger btn-sm" type="submit">
                                    <i class="fa fa-trash-o"></i> 删除
                                </button>
                              </form>`;
            } else {
                actionHtml = '<span class="text-muted">无操作权限</span>';
            }
            
            return actionHtml;
        },
        "orderable": false // 操作列不参与排序
    }
    // 其他列配置...
]

四、双重权限校验保障

前端渲染控制仅为用户体验优化,必须在后端接口层面做权限校验:

  1. 给编辑、删除等敏感接口添加@PreAuthorize注解:
@PreAuthorize("hasAuthority('EDITOR')")
@PostMapping("/touchPoint/delete")
public String deleteTouchPoint(@RequestParam Long id) {
    // 删除业务逻辑
}

@PreAuthorize("hasAuthority('EDITOR')")
@GetMapping("/touchPoint/edit/{id}")
public String editTouchPointPage(@PathVariable Long id, Model model) {
    // 编辑页面跳转逻辑
}
  1. 开启Spring Security方法级权限校验:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    // 其他安全配置...
}

内容的提问来源于stack exchange,提问作者Jaiylon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 15:19:52