[英]Calling static methods in Play! framework controller doesn't work
I have a Play! 我有戏! framework with two actions which contain redundant code.
具有两个包含冗余代码的操作的框架。 So I factored this code into a
private static
method, but It doesn't work anymore then. 因此,我将此代码分解为一个
private static
方法,但此后不再起作用。
public static void show(long itemId, String listId) {
render(getItem(itemId, listId));
}
private static Item getItem(long itemId, String listId) {
// otherwise duplicate code ...
return item;
}
If I inline the code contained in getItem
into the show
action everything is fine: 如果我将
getItem
包含的代码内联到show
action中,一切都很好:
// this works
public static void show(long itemId, String listId) {
Item item = // duplicate code ...
render(item);
}
Why can I not call other static methods within a Play! 为什么不能在Play中调用其他静态方法! controller?
控制器?
Solution 解
Thanks to 'Codemwnci' I've implemented the following solution: 感谢“ Codemwnci”,我实现了以下解决方案:
public static void show(long itemId, String listId) {
renderArgs.put("item", getItem(itemId, listId));
render();
}
I prefer renderArgs
because it makes the intention more clear than a local variable. 我更喜欢
renderArgs
因为它使意图比局部变量更清晰。
When you pass a local variable into the render method, the name of the local variable is used when passed through to the Groovy view. 当您将局部变量传递给render方法时,传递给Groovy视图时将使用局部变量的名称。 In your example, you are not passing a local variable, therefore Play does not know what name to give the item you have specified.
在您的示例中,您没有传递局部变量,因此Play不知道给您指定的项目赋予什么名称。
You have a couple of options. 您有两种选择。 You can do either
你可以做
Option 1 is probably the most sensible. 选项1可能是最明智的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.