简体   繁体   English

在Java Web应用程序中存储和访问资源文件的最佳实践

[英]Best practices to store and access resource files in java web application

I have a bunch of text, xml and other files (ie resources) that I need to access using servlets in java web app. 我有一堆文本,xml和其他文件(即资源),我需要使用java web app中的servlet访问。 For example, there is an xml file, a part of which is returned with a servlet by a user query. 例如,有一个xml文件,其中一部分由用户查询返回servlet。 I am using Tomcat. 我正在使用Tomcat。 What is the best practice to store these files and access them from java code? 存储这些文件并从java代码访问它们的最佳实践是什么? 1) What are the default folders where should I put them, do I need to put them into Web archive or into one of the Jars? 1)我应该在哪里放置默认文件夹,是否需要将它们放入Web存档或其中一个Jars中? 2) How to access the files from java code? 2)如何从java代码访问文件? How can I set the path to them so it will work in any environment? 如何设置它们的路径,以便它可以在任何环境中工作? PS I've read a number of posts related to this topic, most of which recommend to store resources in jars and access them using java.lang.Class.getResourceAsStream(String). PS我已经阅读了许多与此主题相关的帖子,其中大多数都建议将资源存储在jar中并使用java.lang.Class.getResourceAsStream(String)访问它们。 It seems strange because classes and data should be separated. 这看起来很奇怪,因为类和数据应该分开。

It's perfectly fine to load static resources using the classloader. 使用类加载器加载静态资源非常好。 That's what ResourceBundle does to load the internationalized properties files for example. 这就是ResourceBundle为加载国际化属性文件所做的事情。

Put them in WEB-INF/classes along with your class files, or in a jar inside WEB-INF/lib , and load them with the ClassLoader as indicated by the answers you already read. 将它们与您的类文件一起放在WEB-INF/classes ,或者放在WEB-INF/lib中的jar中,然后使用ClassLoader加载它们,如您已经阅读的答案所示。

That doesn't forbid you to place these files in a separate directory from the Java source files in your project. 这并不禁止您将这些文件放在与项目中的Java源文件不同的目录中。 The build process should just make sure to put them in the appropriate location for runtime. 构建过程应该确保将它们放在运行时的适当位置。 The Maven and Gradle convention is to put the source files under src/main/java and the resource files under src/main/resources . Maven和Gradle约定是将源文件放在src/main/java ,将资源文件放在src/main/resources

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM