model-view-controller - 电话号码的Grails网址映射

标签 model-view-controller grails groovy

我想进行设置,以便当用户使用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闭包是否有用,因为它会将User作为对象返回,并且我似乎既不能使用getId()也不可以使用.id。检索ID的对象。

解决/解决方案:

我通过在Controller中创建另一个名为profile的 Action 来解决此问题,然后该 Action 具有类似于以下代码:

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")`

因此,当用户将电话号码输入系统(或/之后的任何字符串)时,它将把用户转到用户/配置文件操作,该操作将尝试通过其电话号码查找用户。如果成功,将向用户显示详细信息,否则将显示错误消息。

最佳答案

如果您使用与 Controller 名称不同的url路径,可能会在以后为您省去一些麻烦。因此,如果您有类似以下内容:

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

您将没有与多个URLMapping条目匹配的任何URL模式,这可能会引起一些混淆。我猜只是:
"/$phoneNumber"(controller:profile, action:show)

会起作用,但是除非您非常小心,否则Grails会因匹配同一请求路径的多个URLMapping感到困惑而最终失败。

关于model-view-controller - 电话号码的Grails网址映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7472075/

相关文章:

Grails 1.4 - ApplicationHolder、ConfigurationHolder 等发生了什么?

groovy - 从字符串中获取 IP 地址(Groovy)

php - MVC现在是编写PHP的唯一方式吗?

javascript - 当 initcomponent 加载 store extjs 4.1.1 时, View 不显示 store

javascript - 了解 express.js/sails.js Controller 范围内的下一个中间件

javascript - Grails如何在没有资源插件的情况下处理静态文件?

java - 如何在Spring Boot MVC中更改View上的数据?

grails - Grails Groovy代码内部值

android - 在Android插件任务上调用doFirst

Groovy 闭包和带有函数参数的重载方法