升级Spring Boot 3与Java 17时遇Freemarker JSPTaglib问题
Spring Boot 3 下 Freemarker 集成 Spring Security 标签的解决方案
问题背景
原Spring Boot 2中通过JSP Taglib桥接方式使用的Spring Security Freemarker标签,升级到Spring Boot 3后失效,且原依赖的TaglibFactory类已被移除。
解决步骤
1. 切换为Spring Security原生Freemarker标签库
Spring Boot 3(基于Spring Framework 6)提供了原生的Freemarker Security标签集成,无需再依赖JSP Taglib桥接。
2. 添加配置类注册标签库
创建Freemarker配置类,将Spring Security标签库注册到Freemarker的配置中:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.web.servlet.support.SecurityWebMvcUtils; import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurerCustomizer; @Configuration public class FreemarkerSecurityConfig { @Bean public FreeMarkerConfigurerCustomizer securityTaglibCustomizer() { return configurer -> configurer.getConfiguration() .setSharedVariable("security", SecurityWebMvcUtils.getSecurityTagLibrary()); } }
3. 模板中直接使用标签
无需再通过<#assign security=JspTaglibs[...]>赋值,直接使用标签即可:
<@security.authorize access="isAuthenticated()"> <@security.authentication property="principal.username"/> </@security.authorize>
说明
Spring Framework 6移除了TaglibFactory等JSP相关过时API,官方推荐使用原生的视图技术集成方式。上述方案通过SecurityWebMvcUtils.getSecurityTagLibrary()获取Spring Security为Freemarker专门实现的标签库,完全适配Spring Boot 3环境。
内容的提问来源于stack exchange,提问作者Shyam
相关产品推荐
相关产品推荐

