简体   繁体   English

在GWT的服务器端加载JSON文件

[英]Load JSON File on the server side in GWT

I have a GWT application and I load a .json file on the server side like this: 我有一个GWT应用程序,并在服务器端加载了一个.json文件,如下所示:

InputStream source = new FileInputStream(testFile.json); 

This works perfectly when I start the application directly in eclipse. 当我直接在eclipse中启动应用程序时,这非常有效。 However, when I deploy the app on tomcat, it does not work. 但是,当我在tomcat上部署应用程序时,它不起作用。 It seems like, that the application is looking for that file in the bin folder of tomcat (???). 看来,该应用程序正在tomcat(???)的bin文件夹中寻找该文件。 However, the correct path would be tomcat/webapps/myProject/testFile.json. 但是,正确的路径是tomcat / webapps / myProject / testFile.json。

Does anyone know how to get the correct path (without harcoding it)? 有谁知道如何获得正确的路径(不对其进行编码)?

The FileInputStream locates files depending on the current working directory, which in turn depends on the way how you started the application, which in turn is thus not controllable from inside your application. FileInputStream根据当前工作目录查找文件,而当前工作目录又取决于您启动应用程序的方式,因此,这又无法从应用程序内部进行控制。 In case of web applications, you need ServletContext#getResourceAsStream() instead of FileInputStream to obtain web application's own resources. 对于Web应用程序,您需要ServletContext#getResourceAsStream()而不是FileInputStream来获取Web应用程序自己的资源。 It takes a path which is relative to the web content folder. 它采用相对于Web内容文件夹的路径。

InputStream input = getServletContext().getResourceAsStream("/testfile.json");
// ...

See also: 也可以看看:

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

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