有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

spring java仅向登录用户显示注销按钮

我在网上搜索了一个解决方案,但我想不出来

我将Spring Boot与Maven一起使用,并拥有
spring boot starter在我的pom中支持ELEAF依赖性。xml文件

我试图使用Thymeleaf显示注销按钮,仅当用户登录时,但此代码似乎不起作用:

<div th:if="${#authorization.expression('isAuthenticated()')}">
   <div class="navbar-form navbar-right">
      <a href="/logout">
            <button type="text" class="btn btn-primary navbar-right">Logout</button>       
      </a>
   </div>
</div>

它不断显示这个错误:

There was an unexpected error (type=Internal Server Error, status=500).
Exception evaluating SpringEL expression: "#authorization.expression('isAuthenticated()')" 

和行号,在那里我有“如果”的条件与百里叶

我该如何解决这个问题


共 (1) 个答案

  1. # 1 楼答案

    可以使用sec:authorize="isAuthenticated()",但可能需要为此添加依赖项等。我用过:

    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity4</artifactId>
        <version>2.1.2.RELEASE</version>
        <scope>compile</scope>
    </dependency>
    

    另外,确保添加SpringSecurityDialect,这样isAuthenticated和其他类似的表达式可以由Spring计算。例:

    @Bean
    public SpringTemplateEngine templateEngine() {
       SpringTemplateEngine engine = new SpringTemplateEngine();
       engine.setTemplateResolver(templateResolver());
       engine.addDialect(new SpringSecurityDialect());
       return engine;
    }
    

    在html页面本身中,向<html>标记添加以下内容,以确保sec:标记被识别:

    xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"