如何在java EE中获取web项目的根路径

如何在java EE中获取web项目的根路径

问题描述:

我正在将 Java EE 用于我的动态 Web 项目.我把 sitemap.xml 文件放在根路径中.现在我需要修改该文件的路径.我试试:

I'm using java EE for my dynamic web project. And i put sitemap.xml file in the root path. Now i need a path to that file to modify. I try:

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

但是系统找不到指定的文件.我正在使用窗口,当我将项目上传到 linux 托管时需要更改什么?

but 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?

ClassLoader#getResource() 仅查找类路径资源,而不查找 Web 资源.sitemap.xml 显然是一个网络资源.您应该使用 ServletContext#getResource(),或者它的 JSF 对应物 ExternalContext#getResource() —根据您的问题历史记录,您使用的是 JSF.

The ClassLoader#getResource() only finds classpath resources, not web resources. The sitemap.xml is clearly a web resource. You should be using ServletContext#getResource() instead, or its JSF counterpart ExternalContext#getResource() — as indicated by your question history, you're using JSF.

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

或者,仅供阅读:

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.

与具体问题无关,写它是一个完整的故事.类路径资源和 Web 资源均不打算从 Java EE 应用程序内部写入.即使有可能(即它不是内存资源),只要您重新部署 WAR 或什至只是重新启动服务器,所有更改都会完全丢失,原因很简单,这些更改未反映在原始文件中WAR 文件.鉴于sitemap.xml"的特定文件名,我的印象是您打算进行更永久的存储.在这种情况下,我强烈建议寻找不同的解决方案.例如.将文件存储在 WAR 之外的固定路径中,或者只是将数据结构存储在数据库中.

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. Even if it were possible (i.e. 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. Given the specific filename of "sitemap.xml", I have the impression that you intented a more permanent storage. In that case, I strongly recommend to look for a different solution. E.g. store the file in a fixed path outside the WAR, or just the data structure in a database.