Spring MVC -使用属性文件作为Country字段的查找表



在我的属性文件中,我将有ff.

country.1=Afghanistan
country.2=Albania
country.3=Algeria
country.4=Andorra
country.5=Angola

,我想在我的视图中有这样的东西,

Country: <form:select path="customer">
    <form:options items="${countries}" />
</form:select>

,然后生成以下html。

<select>
    <option value="1">Afghanistan</option>
    <option value="2">Albania</option>
    <option value="3">Algeria</option>
    <option value="4">Andorra</option>
    <option value="5">Angola</option>
</select>
你对如何做到这一点有什么建议吗?谢谢。

你可以只用一个属性来存放你的国家列表:

=国家阿富汗,阿尔巴尼亚,…

你可以在视图控制器中使用@PropertySource("classpath: countries .properties")注释类,并在环境变量中自动绑定,从而访问属性文件:

@Controller
@PropertySource("classpath:countries.properties")
public class PersistenceConfig {
    @Autowired
    private Environment env;

然后你可以通过调用env.getProperty(")来获得一个属性。你可以将它添加到你的主视图模型中:

@RequestMapping(value={"/","/index","/index.htm","index.html"})
public String indexHtml(ModelMap model) {
    model.addAttribute("countries", env.getProperty("whatever")); 
    return "index"; // or whatever the name of your view is

然后在index.jsp中,您可以简单地使用${nations}来获取这些值,并对它们做任何您想做的事情。在某些情况下,您显然需要将整个字符串解析为一个数组。

也可以将属性文件直接读入.jsp文件。很多人都在讨论这个

最新更新