Spring Security登出时出现Attoparser解析异常问题求助
问题分析
登出后#authentication对象为null,Thymeleaf会优先解析th:text中的表达式,再执行th:if的条件判断,直接访问#authentication.principal.username会触发空指针相关的解析异常。
解决方案
使用Thymeleaf的安全导航运算符(?.),在访问对象属性前先判断对象是否存在,避免空指针问题:
<a th:if="${#authentication?.isAuthenticated()}" th:text="${#authentication.principal.username + '님'}"></a>
如果想进一步确保表达式在任何状态下都能安全解析,也可以给principal和username都加上安全判断:
<a th:if="${#authentication?.isAuthenticated()}" th:text="${#authentication?.principal?.username + '님'}"></a>
或者结合三元表达式简化写法,同时处理登录/登出两种状态:
<a th:text="${#authentication?.isAuthenticated() ? #authentication.principal.username + '님' : ''}"></a>
内容的提问来源于stack exchange,提问作者이규환
相关产品推荐
相关产品推荐

