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

Spring Boot中结合Security Context渲染Thymeleaf模板为字符串

解决方案

1. 使用WebContext替代普通Context

Thymeleaf的Spring Security方言要求上下文实现IWebContext才能获取认证信息,因此在控制器中直接用WebContext替换普通Context即可解决问题。WebContext依赖当前请求的HttpServletRequest和HttpServletResponse,可直接从控制器方法参数中获取:

@Autowired
private ISpringTemplateEngine templateEngine;

@GetMapping("/your-api-path")
public ResponseEntity<Map<String, String>> getRenderedHtml(HttpServletRequest request, HttpServletResponse response) {
    // 初始化业务数据
    DynamicDetailInfo dynamicDetailInfo = new DynamicDetailInfo();
    // ... 填充数据逻辑

    // 创建WebContext,传入请求、响应、Servlet上下文及当前Locale
    WebContext context = new WebContext(
        request, 
        response, 
        request.getServletContext(), 
        LocaleContextHolder.getLocale()
    );
    context.setVariable("dynamicDetailInfo", dynamicDetailInfo);

    // 渲染模板片段
    String html = templateEngine.process(
        "includes/_fragment", 
        Collections.singleton("absenceDynamicDetail"), 
        context
    );

    // 返回JSON结果
    return ResponseEntity.ok(Collections.singletonMap("renderedHtml", html));
}

2. 非Web环境下手动注入Security上下文

如果是在无HttpServletRequest的场景(比如定时任务、后台服务),可以手动将当前用户的认证信息注入到普通Context中:

@Autowired
private ISpringTemplateEngine templateEngine;

public String renderTemplateInBackground() {
    DynamicDetailInfo dynamicDetailInfo = new DynamicDetailInfo();
    // ... 填充数据逻辑

    Context context = new Context();
    context.setVariable("dynamicDetailInfo", dynamicDetailInfo);

    // 从SecurityContextHolder获取当前认证信息并注入上下文
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    if (authentication != null) {
        context.setVariable("authentication", authentication);
        // 也可使用SpringSecurityDialect工具类完成注入
        SpringSecurityContextUtils.setAuthentication(context, authentication);
    }

    return templateEngine.process(
        "includes/_fragment", 
        Collections.singleton("absenceDynamicDetail"), 
        context
    );
}

可搜索的关键词

  • Thymeleaf WebContext Spring Security
  • Thymeleaf sec:authorize 非Web上下文
  • Thymeleaf 手动渲染模板 权限认证
  • SpringSecurityDialect 上下文配置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 15:09:57