【问题标题】:Variable not working in a GSP Tag, but working in normal Text变量在 GSP 标签中不起作用,但在普通文本中起作用
【发布时间】:2011-08-15 10:33:45
【问题描述】:

我想让登录的用户可以通过快速链接编辑他的用户帐户。

为此,我使用正确的 GSP 标签创建了一个链接,并且我想使用正确的 Helper 从 Spring Security UserDetails 对象传递用户 ID。

问题在于,当我在 GSP 标记中时,例如在编辑我的用户之后,但不是在我真正需要的地方,在 id 属性中,这有效。

<g:link controller="user" action="show" id="${sec.loggedInUserInfo(field: "id")}">
    Edit my User ${sec.loggedInUserInfo(field: "id")}
</g:link>

预期:

<a href="/Backoffice/user/show/1"> Edit my User 1 </a>

错误的结果:

<a href="/Backoffice/user/show"> Edit my User 1 </a>

安全标签库正在访问的 UserDetails 类在这里:

   import org.codehaus.groovy.grails.plugins.springsecurity.GrailsUser
   import org.springframework.security.core.GrantedAuthority

   class UserDetails extends GrailsUser {
       final String displayName
       final String email
       final String gravatarImage

   ...

id 在 GrailsUser 基类中定义为 Object。

类 GrailsUser 扩展用户 {

private final Object _id

    ...

}

并且会在此处编码为 HTML:

/**
 * Renders a property (specified by the 'field' attribute) from the principal.
 *
 * @attr field REQUIRED the field name
 */
def loggedInUserInfo = { attrs, body ->

    // TODO support 'var' and 'scope' and set the result instead of writing it

    String field = assertAttribute('field', attrs, 'loggedInUserInfo')

    def source
    if (springSecurityService.isLoggedIn()) {
        source = determineSource()
        for (pathElement in field.split('\\.')) {
            source = source."$pathElement"
            if (source == null) {
                break
            }
        }
    }

    if (source) {
        out << source.encodeAsHTML()
    }
    else {
        out << body()
    }
}

有趣的是:这行得通。但我真的很想对链接使用一致的 gsp 语法,我想了解为什么上面发布的代码不起作用。

<a href="${createLink( controller : "user", action : "show", id : sec.loggedInUserInfo(field: "id"))}">Edit my User</a>

【问题讨论】:

    标签: grails spring-security gsp


    【解决方案1】:

    看起来引用错误 - 您需要在 id="..." 内转义 "。为简单起见,请尝试使用field: 'id' 而不是field: "id"

    【讨论】:

    • 非常感谢,成功了。有趣的是,IDEA 没有显示明显的错误...
    • 我用 Grails 向 IDEA 报告了一大堆错误 - 它们很快就被修复了。
    【解决方案2】:

    您需要将 id 作为参数传递,您只是将 id 分配给您的链接..

    <g:link controller="user" action="show" params="[id:${sec.loggedInUserInfo(field: "id")}]" id="${sec.loggedInUserInfo(field: "id")}">
        Edit my User ${sec.loggedInUserInfo(field: "id")}
    </g:link>
    

    使用firebug 查看 g:link 的准确呈现的 html...

    【讨论】:

      猜你喜欢
      • 2012-01-29
      • 2018-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-09
      • 2012-05-27
      相关资源
      最近更新 更多