【问题标题】:How to use SpEL with hasRole to set html attribute?如何使用带有 hasRole 的 SpEL 来设置 html 属性?
【发布时间】:2019-05-11 14:23:32
【问题描述】:

在 Spring/Thymeleaf 中:我想根据用户是否有 ROLE_A 来设置属性。

  1. 我在下面尝试了 HTML:

<section class="footer" ... th:someattr="#{hasRole('ROLE_A')} ? 'true' : 'false'">

无论用户是否有 ROLE_A,它总是呈现为 <section class="footer" ... someattr="true">

  1. 我也试过 ${hasRole('ROLE_A')} ? 'true' : 'false' 但不起作用 ():

SpelEvaluationException: EL1004E:(pos 0): 方法调用:方法 hasRole(java.lang.String) 找不到 org.thymeleaf.spring4.expression.SPELContextMapWrapper 类型

如何根据分配的身份验证角色将属性设置为 true|false。 谢谢。

【问题讨论】:

    标签: spring thymeleaf spring-el


    【解决方案1】:

    有时,这是由于您的项目配置造成的。因此,让我们做一些更改并使用以下代码。

    <section class="footer" ... th:someattr="${#authorization.expression('hasRole(''ROLE_A'')' ? 'true' : 'false'}">
    

    要使用#authorization,您需要添加以下依赖项thymeleaf-extras-springsecurity4

    <dependency>
        <groupId>org.thymeleaf.extras</groupId>
        <artifactId>thymeleaf-extras-springsecurity4</artifactId>
    </dependency>
    

    如果您使用&lt;artifactId&gt;spring-boot-starter-parent&lt;/artifactId&gt;,则无需向 Thymeleaf Extras 添加任何版本,因为 Spring Boot 会为您管理。如果没有,请尝试添加此版本&lt;version&gt;3.0.4.RELEASE&lt;/version&gt;

    注意:如果不起作用,请将其更改为 thymeleaf-extras-springsecurity5,根据您的 Spring 版本,一个可以工作,另一个不能工作。

    【讨论】:

      【解决方案2】:

      我认为您正在寻找类似的东西:

      <section class="footer" ... th:someattr="${#request.isUserInRole('A') ? 'true' : 'false'}">
      

      (不需要“额外”。)

      【讨论】:

        猜你喜欢
        • 2021-05-26
        • 2011-03-05
        • 1970-01-01
        • 2021-02-03
        • 1970-01-01
        • 1970-01-01
        • 2022-01-11
        • 2016-12-19
        • 1970-01-01
        相关资源
        最近更新 更多