【发布时间】:2013-03-25 17:19:23
【问题描述】:
我可能应该指出,Spring 本身对这个问题并不一定至关重要,但是我在使用 Spring 时遇到了这种行为,所以这个问题使用了我在 Spring 中遇到的情况。
我有一个控制器类,它将对 GET 和 POST 请求的请求映射到特定表单的同一组 URL。此表单针对不同的语言环境有不同的 URL,但对于 GET 请求只有一种方法,而对于 POST 请求只有一种方法,因为表单的控制器级别的逻辑对于每个语言环境站点都是相同的(但更深层次的事情在逻辑中,例如特定于区域设置的验证,可能会有所不同)。示例:
@Controller
public class MyFormController {
// GET request
@RequestMapping(value={"/us-form.html", "/de-form.html", "/fr-form.html"},
method={RequestMethod.GET})
public String showMyForm() {
// Do some stuff like adding values to the model
return "my-form-view";
}
// POST request
@RequestMapping(value={"/us-form.html", "/de-form.html", "/fr-form.html"},
method={RequestMethod.POST})
public String submitMyForm() {
// Do stuff like validation and error marking in the model
return "my-form-view"; // Same as GET
}
}
GET 和 POST 的形式在这样编写时工作得很好。您会注意到用于@RequestMapping 值的String 数组是相同的。我想要做的是将这些 URL 放在一个位置(最好是控制器中的 static final 字段),这样当我们添加新 URL(对应于未来本地化站点中的表单)时,我们可以将它们添加到一个位置.所以我尝试对控制器进行这种修改:
@Controller
public class MyFormController {
// Moved URLs up here, with references in @RequestMappings
private static final String[] MY_URLS =
{"/us-form.html", "/de-form.html", "/fr-form.html"};
// GET request
@RequestMapping(value=MY_URLS, // <-- considered non-constant
method={RequestMethod.GET})
public String showMyForm() {
// Do some stuff like adding values to the model
return "my-form-view";
}
// POST request
@RequestMapping(value=MY_URLS, // <-- considered non-constant
method={RequestMethod.POST})
public String submitMyForm() {
// Do stuff like validation and error marking in the model
return "my-form-view"; // Same as GET
}
}
这里的问题是编译器抱怨value 属性不再是一个常量。我知道 Spring 要求 value 必须是一个常量,但我曾认为将 final 字段(或在我的情况下为 static final)与包含 String 文字的 Array 文字一起使用会传递为“持续的”。我的怀疑是,数组文字必须以这样一种方式动态构建,即在解析 value 属性时它不会被初始化。
我觉得用基本的 Java 知识来弄清楚这不应该是一件难事,但是有些东西让我无法理解,经过一些研究我无法找到任何答案。有人可以证实我的怀疑并给出一个引用或很好的解释来解释为什么会这样,或者否认我的怀疑并解释实际问题是什么?
注意:我不能简单地将这些 URL 组合成一个 Path Pattern,因为每个表单 URL 都使用其本地化站点的语言,并且不可能进行匹配。例如,我只是将上面的“/{locale}-form.html”字符串作为我的 URL。
【问题讨论】:
-
@sp00m 它可能确实是重复的。我不确定这是否是一个骗子,因为那个提问者使用的是方法的返回值,而不是像我这样的文字。
标签: java spring controller constants