gpt4 book ai didi

java - 如何在 Spring MVC 中创建属性文件的列表对象?

转载 作者:行者123 更新时间:2023-11-30 06:55:06 24 4
gpt4 key购买 nike

在属性文件中我有 50 个问题。

Quest1=1.1
Quest1Text=How are ju?

Quest2=1.2
Quest2Text=How are jui?

Quest3=1.3
Quest3Text=How are juieeeeee?

我想用 Java 读取它们并在 JSP 中显示。

互联网上的标准方式是@Value(ques2)variable @Value(quest2Text) variable但这将使我的 Controller 变得笨拙。

你能告诉我如何使用一些 Spring 注释从属性文件中为 java 中的列表赋值吗?

最佳答案

首先,您已将属性文件添加到上下文配置中:

@PropertySource(name = "questions", value = "classpath:question.properties")
public class AppConfig {
...
}

我用了classpath:示例中的前缀(这意味着文件将位于类路径的根目录中),但您可以使用 file: , 指定绝对路径。请注意,源名称指定为 questions .我们将来会需要它。

其次,创建数据容器类。当然你可以用Map<String, String>存储您的问题,但上课会更方便:

public class Quest{
private String number;
private String text;

//getters and setters
....
}

第三,获取controller中的property source并加载numbers和values:

@Controller
public class MyController {

@Autowired
private ConfigurableEnvironment environment;

@RequestMapping("/mymapping")
public String method(ModelMap model){
List<Quest> questList = loadQuestList();
model.addAttribute("questList", questList);
return "myview";
}


private List<Quest> loadQuestList(){

ResourcePropertySource source =
(ResourcePropertySource)environment.getPropertySources().get("questions");

//first get all names of questions like 'Quest1','Quest2' etc
List<String> nameList = new ArrayList<String>();
for(String name : source.getPropertyNames()){
if(!name.endsWith("Text")){
nameList.add(name);
}
}
//unfortunately, default properties are unsorted. we have to sort it
Collections.sort(nameList);

//now, when we have quest names, we can fill list of quests
List<Quest> list = new ArrayList<Quest>();

for(String name : nameList){
String number = source.getProperty(name);
String text = source.getProperty(name+"Text");

Quest quest = Quest();
quest.setNumber(number);
quest.setText(text);
list.add(quest);
}
return list;
}
}

关于java - 如何在 Spring MVC 中创建属性文件的列表对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35738749/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com