在Spring-MVC中访问应用程序属性 [英] Accessing Application Properties in Spring-MVC
问题描述
Spring-MVC新手。
New to Spring-MVC.
我想在.properties文件中存储两个属性(uploadFolder = ..,downloadFolder = ..)和
在HomeController类中访问它(由MVC模板自动创建)。
I want to store two properties (uploadFolder=.., downloadFolder=..) in a .properties file and access it in HomeController class (automatically created by the MVC template).
你能指导我如何...
Can you please guide me how..
1)使用上面的内容创建了一个app.properties文件,并将其放在/ src / main / resources下。这是正确的还是应该在/ webapp / resources下?
1) Created an app.properties file with the above and placed it under /src/main/resources. is this correct or should it go under /webapp/resources?
2)以下面的方式在servlet-context.xml中放置一个bean。这是正确的吗?
2) Placed a bean in servlet-context.xml in the following manner. is this correct?
<beans:bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<beans:property name="basename" value="app" />
</beans:bean>
3)现在如何在Java控制器中访问它?
3) Now how do I access this in Java controllers?
4)如何在JSP中访问这些?
4) How do I access these in a JSP?
我不知道我会多么感谢你。
I can't tell how much I will thank you.
推荐答案
有几种不同的方法可以做到这一点。我做了以下几点。在应用程序上下文中:
There are a few different ways to do it. I do the following. In app context:
<util:properties id="myProps" location="classpath:app.properties" />
确保文件顶部有以下内容以包含util命名空间:
Make sure you have the following at the top of your file to include the "util" namespace:
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation= "... http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"
我通常将我的属性文件放在src / main / resources中。只要他们在课堂上,你就是好人。然后,在您的控制器中,您可以使用以下命令注释您的字段/方法:
I usually put my properties files in src/main/resources. As long as they're on the classpath, you're good. Then, in your controller, you can annotate your field/method with:
@Controller
public class MyController {
@Value("#{myProps['uploadFolder']}")
private String uploadFolder
@Value("#{myProps['downloadFolder']}")
private String downloadFolder
@RequestMapping("myPage")
public String loadPage(ModelMap m) {
m.addAttribute("uploadFolder", uploadFolder);
m.addAttribute("downloadFolder", downloadFolder);
return "myPage";
}
public void setUploadFolder(String uploadFolder) {
this.uploadFolder = uploadFolder;
}
public void setDownloadFolder(String downloadFolder) {
this.downloadFolder = downloadFolder;
}
}
然后,在你的JSP中:
Then, in your JSP:
Download folder: ${downloadFolder} <br/>
Upload folder: ${uploadFolder}
HTH。如果您有任何问题,请告诉我。
HTH. Let me know if you have any questions.
这篇关于在Spring-MVC中访问应用程序属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!