A very basic question. I want to provide URIs for some objects in my application. For example, a resource is available at:
http://localhost:8080/myapp/user/1
However, I'd like to serialize such a User object. This serialization should contain the public URI of the object itself. So for example, the model has a new method serializeToSomething
, which would serialize:
id: 1
username: JohnDoe
email: johndoe@example.com
publicURI: http://localhost:8080/myapp/user/1
How can I let the model instance know of its URL?
Some notes: This has to happen within the scope of the model, controller or service, and not within the view. Also I don't开发者_Python百科 want to hardcode this.
See related question Can I use grails tag outside of GSP?
Basically you can use g.createLink
in a controller or service, and it will return a string. So you can do something like:
def uri = g.createLink(controller: 'user', action: 'show', id: user.id, absolute: true)
Personally I ended up serializing 3 things: controller
name, action
name (typically "show") and id
. Then I used these three in g.createLink
when displaying deserialized objects in a View.
Sure, this won't work if you need deserialized object for external usage.
You can get the url in a controller using
request.forwardURI
A similar question has been asked before
精彩评论