在Grails控制器的操作中使用'get'会导致即使没有调用也会执行操作 [英] Using 'get' in an action for Grails controllers causes action to execute even when not called
问题描述
grails-app / views / site / home.gsp:
首页
SiteController.groovy:
class SiteController {
def index(){
render(view:home)
}
def getTest(){
rendergetTest
}
}
网站访问localhost:8080 / site来执行SiteController的索引操作。
预期输出:homepage
实际输出: getTest homepage
如果index的渲染操作改为这样:
render(view:home,model:[:])
。
如果在动作名称中包含单词get之前添加了一个字符,则会生成预期的输出。
有趣的是,getTest()在IDEA中用颜色编码为紫色。还应该注意的是,如果你在开始时有多个get单词的方法,它们将全部执行。
这在Grails 1.3.6中不会发生。这可以在全新的Grails 2.2.2项目中重现,并且对我来说似乎是一个错误。为什么会发生这种情况?
GRAILS-9310 表明这是一个已知的限制,不会改变,解决方法不是为你的行为命名 get *
。根本原因是
如果未返回显式模型,则控制器的属性将用作模型( Grails文档)
定义 getTest()
方法时,这意味着控制器具有 test
属性,并且当您在没有显式模型的情况下呈现主视图视图,控制器属性被枚举以形成模型映射。 getTest()
方法将作为此枚举过程的一部分被调用。
如果您确实需要 getTest
出现在URL中,那么您必须将实际操作命名为其他名称,然后定义自定义URL映射以指导 / controller / getTest
重命名操作的URI。
Issue: A controller's action has a render tag without passing in a model. There exists an action that begins with the word 'get'.
grails-app/views/site/home.gsp:
homepage
SiteController.groovy:
class SiteController {
def index() {
render (view: "home")
}
def getTest() {
render "getTest"
}
}
The site is accessed at localhost:8080/site to execute the index action of SiteController.
Expected output: homepage Actual output: getTest homepage
If the render action of index is changed to this:
render(view: "home", model: [:])
The expected output is produced.
If a character is added before the word get in the action name, the expected output is produced.
Interestingly enough, getTest() is color coded as purple in IDEA. It should also be noted that if you have multiple methods with the word get at the beginning, they are ALL executed.
This did NOT happen in Grails 1.3.6. This is reproducible in a brand new Grails 2.2.2 project and seems like a bug to me. Why is this happening?
GRAILS-9310 suggests that this is a known limitation which won't be changed, the workaround is not to name your actions get*
. The root cause is
If no explicit model is returned the controller's properties will be used as the model (Grails docs)
When you define a getTest()
method this means that the controller has a test
property, and when you render the "home" view without an explicit model the controllers properties get enumerated to form the model map. The getTest()
method will be called as part of this enumeration process.
If you really need getTest
to appear in the URL then you'll have to name the actual action something else and then define a custom URL mapping to direct the /controller/getTest
URI to the renamed action.
这篇关于在Grails控制器的操作中使用'get'会导致即使没有调用也会执行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!