java-仅向登录的用户显示注销按钮 [英] java - Showing the logout button only to logged users
问题描述
我已经在网上搜索了解决方案,但我不知道如何解决.
I've searched the web for a solution, but I can't figure this out.
我正在将Spring Boot与Maven结合使用,并且具有
我的pom.xml文件中的spring-boot-starter-thymeleaf依赖项.
I'm using Spring Boot with Maven and have the
spring-boot-starter-thymeleaf dependency in my pom.xml file.
仅在用户登录后,我才尝试使用Thymeleaf显示注销按钮,但是此代码似乎无效:
I'm trying to show the logout button, using Thymeleaf, only if the user is logged in, but this code doesn't seem to work:
<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()')"
以及与百里香具有"if"条件的行号.
and the line number where I have the "if" condition with thymeleaf.
我该如何解决?
推荐答案
您可以使用sec:authorize="isAuthenticated()"
,但是您可能需要为此添加依赖项等.我用过:
You could use the sec:authorize="isAuthenticated()"
, but you might have to add the dependencies etc for this. I used:
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>2.1.2.RELEASE</version>
<scope>compile</scope>
</dependency>
此外,请确保添加SpringSecurityDialect
,以便Spring可以评估isAuthenticated和其他类似的表达式.例如:
Also, make sure to add the SpringSecurityDialect
so that isAuthenticated and other similar expressions can be evaluated by Spring. ex:
Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setTemplateResolver(templateResolver());
engine.addDialect(new SpringSecurityDialect());
return engine;
}
对于html页面本身,将以下内容添加到<html>
标记中,以确保识别出sec:
标记:
To the html page itself, add the following to the <html>
tag to make sure the sec:
tag is recognized:
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"
这篇关于java-仅向登录的用户显示注销按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!