【发布时间】: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