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

Spring Boot 3+Thymeleaf:根据当前URL为链接动态添加active类

在Spring Boot 3 + Thymeleaf中实现导航链接的active类切换

Spring Boot 3升级后,Thymeleaf默认不再将HttpServletRequest这类对象作为上下文变量暴露,所以你之前用#request的写法会报错。下面是几种可行的解决办法:

方法1:通过#ctx直接获取请求对象(最快改法)

不用额外配置,直接修改Thymeleaf表达式,通过上下文对象#ctx获取请求实例:

<a th:href="@{/application}" th:classappend="${#ctx.getRequest().getRequestURI() == '/application' ? 'active' : ''}">应用管理</a>

方法2:全局注入当前URI到模型(更优雅)

写一个全局的控制器增强类,把当前请求的URI注入到所有请求的模型中,所有页面都能直接复用:

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;

@ControllerAdvice
public class GlobalRequestAttributes {
    @ModelAttribute("currentUri")
    public String getCurrentRequestUri(HttpServletRequest request) {
        return request.getRequestURI();
    }
}

页面里可以简化写法:

<a th:href="@{/application}" th:classappend="${currentUri == '/application' ? 'active' : ''}">应用管理</a>

方法3:控制器中指定当前激活页面(最灵活)

如果你的URI结构复杂,或者不想硬写URI字符串,可以在每个控制器方法里,给模型添加一个标识当前页面的属性:

@GetMapping("/application")
public String applicationPage(Model model) {
    model.addAttribute("activePage", "application");
    return "application";
}

页面里直接判断这个标识:

<a th:href="@{/application}" th:classappend="${activePage == 'application' ? 'active' : ''}">应用管理</a>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 17:27:10