简体   繁体   English

如何在Java EE中获取Web项目的根路径

[英]How to get the root path of a web project in java EE

I'm using java EE for my dynamic web project. 我将Java EE用于动态Web项目。 And i put sitemap.xml file in the root path. 然后将sitemap.xml文件放在根路径中。 Now i need a path to that file to modify. 现在,我需要修改该文件的路径。 I try: 我尝试:

String path = getClass().getClassLoader().getResource(".").getPath() +"\\sitemap.xml";

but The system cannot find the file specified . 但是The system cannot find the file specified I'm using window, what do i need to change when i upload my project to linux hosting? 我正在使用窗口,将项目上传到linux托管时需要更改什么?

The ClassLoader#getResource() only finds classpath resources, not web resources. ClassLoader#getResource()仅查找类路径资源,而不是Web资源。 The sitemap.xml is clearly a web resource. sitemap.xml显然是Web资源。 You should be using ServletContext#getResource() instead, or its JSF counterpart ExternalContext#getResource() — as indicated by your question history, you're using JSF. 您应该改用ServletContext#getResource()或它的JSF对应的ExternalContext#getResource() -如您的问题历史记录所示,您正在使用JSF。

URL url = externalContext.getResource("/sitemap.xml");

Or, for reading only: 或者,仅用于阅读:

InputStream input = externalContext.getResourceAsStream("/sitemap.xml");

Generally, you shouldn't be interested at all in the actual disk file system path being used. 通常,您对所使用的实际磁盘文件系统路径完全不感兴趣。 This is usually a temporary folder location or even an in-memory location. 这通常是一个临时文件夹位置,甚至是一个内存位置。


Unrelated to the concrete question, writing to it is a whole story apart. 具体问题无关,为此写信是一个完整的故事。 Neither classpath resources nor web resources are intented to be writable from inside the Java EE application. 类路径资源和Web资源都不能从Java EE应用程序内部写入。 Even if it were possible (ie it's not an in-memory resource), all changes would get completely lost whenever you redeploy the WAR or even when you just restart the server, for the very simple reason that those changes are not reflected in the original WAR file. 即使有可能(即它不是内存中的资源),无论何时重新部署WAR或什至只是重新启动服务器,所有更改都将完全丢失,原因很简单,即这些更改未反映在原始服务器中WAR文件。 Given the specific filename of "sitemap.xml", I have the impression that you intented a more permanent storage. 给定特定的文件名“ sitemap.xml”,我的印象是您打算使用一个更永久的存储。 In that case, I strongly recommend to look for a different solution. 在这种情况下,强烈建议您寻找其他解决方案。 Eg store the file in a fixed path outside the WAR, or just the data structure in a database. 例如,将文件存储在WAR之外的固定路径中,或者仅存储在数据库中的数据结构中。

First of all, try not to use windows file separator "\\", cause it's platform dependent. 首先,请尽量不要使用Windows文件分隔符“ \\”,因为它与平台有关。 Instead, you can use "/" (as far as I remember, it should be replaced by JVM to suitable separator) or, even better, File.separator . 相反,您可以使用“ /”(据我所知,应该使用JVM将其替换为合适的分隔符),或者甚至可以使用File.separator

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

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