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
相关产品推荐
相关产品推荐

