【问题标题】:Grails UrlMappings for a telephone number电话号码的 Grails UrlMappings
【发布时间】:2011-09-19 13:54:16
【问题描述】:

我想设置它,这样当用户使用 URL 中的电话号码访问应用程序时,Grails 会将用户定向到指定的配置文件,例如:

localhost:8080/Application/profile/07871216969 -> /user/show/User.findByUserTelephone(07871216969)

或者最好是

localhost:8080/Application/07871216969 -> /user/show/User.findByUserTelephone(07871216969)

但是,我不知道在调用 findByUserTelephone 闭包时如何引用 URL 中的电话号码;我注意到类似的东西:

/profile/$telephoneNumber 但是我不完全确定它是如何工作的。

另外,由于 /user/show 操作需要参数中的 id,我不确定 findUserByTelephone 闭包是否有用,因为它将用户作为对象返回,而且我似乎无法使用 getId() 或.id 要检索 id 的对象。

已解决/解决方案:

我通过在控制器中创建另一个名为profile 的动作解决了这个问题,该动作的代码类似于以下:

def profile = {
    if(User.findByUserTelephone(params.userTelephone)) {
        def userInstance = User.findByUserTelephone(params.userTelephone)

        if (!userInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])}"
            redirect(action: "list")
        }
        else {
            [userInstance: userInstance]
        }
    } else {
        render("Sorry, that user wasn't found in our database.")
    }
}

然后我创建了以下 UrlMapping 条目:

`"/$userTelephone"(controller: "user", action: "profile")`

因此,当用户在系统中输入电话号码(或/ 之后的任何字符串)时,系统会将用户路由到用户/个人资料操作,该操作将尝试通过电话号码查找用户。如果成功,将显示用户详细信息,否则将显示错误消息。

【问题讨论】:

    标签: model-view-controller grails groovy


    【解决方案1】:

    如果您使用与控制器名称不同的 url 路径,以后可能会为您省去一些麻烦。所以如果你有类似的东西:

    "/p/$phoneNumber"(controller:profile, action:show)
    

    您不会有任何与多个 URLMapping 条目匹配的 URL 模式,这可能会让人有点困惑。我猜只是:

    "/$phoneNumber"(controller:profile, action:show)
    

    会起作用,但我希望 Grails 会被多个匹配相同请求路径的 URLMapping 弄糊涂,除非你非常小心。

    【讨论】:

    • 是的,我在编写上面的 UrlMapping 并做了类似的事情后不久就遇到了问题。谢谢。 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-15
    • 2010-11-17
    相关资源
    最近更新 更多