我对 Spring MVC 有点陌生。在处理项目时,有一个用例,我需要从文件中获取一些数据并将其填充到 jsp 中。
public HashMap<String, HashMap<String, ArrayList<String>>> getFooterMoreLinks(){
HashMap<String, HashMap<String, ArrayList<String>>> myArray = new HashMap<String, HashMap<String, ArrayList<String>>>();
HashMap<String, ArrayList<String>> valueArr = new HashMap<String, ArrayList<String>>();
valueArr.put("heading",new ArrayList<String>() {{add("More Links");} } );
valueArr.put("row1",new ArrayList<String>() {{add("About-us");add("http://www.example.com");} } );
valueArr.put("row2",new ArrayList<String>() {{add("Investor Relation");add("http://www.example.com");} } ); //so on
myArray.put("more_links", valueArr);
HashMap<String, ArrayList<String>> partnerSiteLinksArray = new HashMap<String, ArrayList<String>>();
partnerSiteLinksArray.put("heading" ,new ArrayList<String>() {{add("Partner Heading");} } );
partnerSiteLinksArray.put("row1" ,new ArrayList<String>() {{add("Support");add("http://www.example.com");} } );
partnerSiteLinksArray.put("rowe" ,new ArrayList<String>() {{add("Daily Deails");add("http://www.example.com");} } ); //so on
myArray.put("partner_programs", partnerSiteLinksArray);
}
并在jsp中填充myArray
。一切工作正常,但我需要从文件中选择所有这些硬编码值。请帮忙!因为.properties文件不支持类似数组的格式。
最佳答案
在 .properties 文件中存储配置
然后你需要有你的.properties
文件,它是标准的java属性文件,格式如下:
foo.properties
some.property.key=42
someother.property.key=Username has to be at least 5 characters long
有关 .properties 文件的格式和用法的更多信息,请参阅 here .
让你的属性对 spring 可见
首先,您需要声明 spring 用于访问属性文件的 bean。
<bean id="myProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath*:foo.properties</value>
<value>classpath*:bar.properties</value>
</list>
</property>
</bean>
或者当你使用Spring Java Configuration时,你必须使用
@PropertySource("classpath:/com/myco/app.properties")
在 Spring beans 中使用值
然后您就可以通过 Java 类中的属性对象访问属性文件。
@Component
class MyClass {
@Resource(name="foo")
private Properties fooProperties;
@Resource(name="bar")
private Properties barProperties;
//Use your properties as neccessary
}
或者,您可以直接从属性文件注入(inject)具体值。当您的值较少时,这会更简单。在 @Value 注释中,您使用属性名称(键)来注入(inject)其值
@Value("${some.property.key}")
private String value;
关于java - 在文件中保存数据的文件格式以及如何读取此数据 - Spring MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29080846/