如何在Java程序(J2EE + JSTL)中获取服务器文件夹的路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/918396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:04:07  来源:igfitidea点击:

how to get the path of server's folder inside Java program (J2EE + JSTL)

javajakarta-ee

提问by AGeek

I wanted to read contents of Excel files in my web-based project (J2EE-JSP+Servlets) which are located inside the web server's folder.

我想读取位于 Web 服务器文件夹内的基于 Web 的项目 (J2EE-JSP+Servlets) 中 Excel 文件的内容。

I have made a java file, which i will call through a JSP page using JSTL library, but I need to get the path of the Excel sheet in the Java file, so I can read the contents.

我已经制作了一个java文件,我将使用JSTL库通过JSP页面调用它,但是我需要在Java文件中获取Excel工作表的路径,以便我可以读取内容。

How can I get the path to the current Java file and so the Excel file?

如何获取当前 Java 文件以及 Excel 文件的路径?

Also, I will be reading the contents of the Excel file through POI library. I was able to do this in J2SE development, but is it possible here?

此外,我将通过 POI 库读取 Excel 文件的内容。我能够在 J2SE 开发中做到这一点,但在这里有可能吗?

POIFSFileSystem fs = null;
    try {
        fs = new POIFSFileSystem(new FileInputStream("**some path here of sheet**"));
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    HSSFWorkbook wb = null;
    try {
        wb = new HSSFWorkbook(fs);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    HSSFSheet sheet = wb.getSheetAt(0);
    HSSFRow row;
    HSSFCell cell1,cell2,cell3; 

    int rows; // No of rows, stores the no. of rows for an excel sheet
    int cols; // No of columns, stores the no. of columns for an excel sheet

    rows = sheet.getPhysicalNumberOfRows();
    cols = 5;

    for(int r = 0; r < rows; r++) {
        row = sheet.getRow(r);

        if(row != null) {
            cell1 = row.getCell(1);
            cell2 = row.getCell(2);
            cell3 = row.getCell(4);

            //System.out.println(cell1.getStringCellValue()+" "+cell2.getStringCellValue()+" "+cell3.getStringCellValue());                
        }
    }
}

回答by Slartibartfast

You can ask servlet context to translate relative to real path:

您可以要求 servlet 上下文相对于实际路径进行转换:

context.getRealPath("/");

If you java class is servlet, you can probably do something like

如果你的java类是servlet,你可能可以做类似的事情

getServletConfig().getServletContext();

otherwise, jsp page is a servlet, so you can pass it from there.

否则,jsp 页面是一个 servlet,因此您可以从那里传递它。

Finally, you can pick it up once when you start your app:

最后,您可以在启动应用程序时选择一次:

public class AppStartup implements ServletContextListener {

    public void contextDestroyed(ServletContextEvent event) {
    }

    public void contextInitialized(ServletContextEvent event) {
        ServletContext context = event.getServletContext();
        // remember it in some static class for future use
    }
}

Having said all this, it's probably better to make a servlet that has his servlet context, resolve path, and call your class with resolved path to a file, then finally forward request to a jsp page to display results.

说了这么多,最好制作一个 servlet,它有他的 servlet 上下文,解析路径,并用解析的文件路径调用你的类,然后最后将请求转发到一个 jsp 页面以显示结果。

回答by Martin McNulty

I suspect if you're looking for the local filesystem path on the server it may not be possible. Although some web application servers (notably Tomcat, I think) do have a folder containing all of your app's files, there are others that run apps directly from a compressed WAR file. In this case there may not be a path to your Excel file as it would be inside an archive.

我怀疑如果您正在寻找服务器上的本地文件系统路径,这可能是不可能的。尽管一些 Web 应用程序服务器(我认为特别是 Tomcat)确实有一个包含所有应用程序文件的文件夹,但还有其他应用程序服务器直接从压缩的 WAR 文件运行应用程序。在这种情况下,您的 Excel 文件可能没有路径,因为它位于存档中。

One possible way around this that's independent of the application server you're running on would be to package the Excel file inside one of the JARs in WEB-INF/lib, and then read it using

解决此问题的一种可能的方法是将 Excel 文件打包在 .jar 中的一个 JAR 中WEB-INF/lib,然后使用

getClass().getResourceAsStream("/class/path/to/file.xls")

instead of

代替

new FileInputStream("/local/filesystem/path/file.xls")

When using getResourceAsStream("...") you need to supply a class path, rather than a filesystem path. So, if you packaged the Excel file inside a JAR, in a package called com.yourcompany.files, you'd need to use

使用 getResourceAsStream("...") 时,您需要提供类路径,而不是文件系统路径。因此,如果您将 Excel 文件打包在 JAR 中,在名为 的包中com.yourcompany.files,您需要使用

getClass().getResourceAsStream("/com/yourcompany/files/file.xls")

回答by victor hugo

In a basic JSP/Servlet app you'd have a backing servlet which will do almost all the logic in your program, pushthe model into a request and then redirect the user to a JSP page that will pullthe model from the request and will only format it (by using JSTL if you want). If your method needs to perform some kind of processing using the Excel file it should be inside a class extending javax.servlet.http.HttpServlet this way you could access the ServletContext and its method

在基本的 JSP/Servlet 应用程序中,您将有一个支持 servlet,它将执行您程序中的几乎所有逻辑,模型送到请求中,然后将用户重定向到一个 JSP 页面,该页面将从请求中提取模型并将只格式化它(如果需要,可以使用 JSTL)。如果您的方法需要使用 Excel 文件执行某种处理,它应该在扩展 javax.servlet.http.HttpServlet 的类中,这样您就可以访问 ServletContext 及其方法

String physicalFolder = getContext().getRealPath("/");

If you don't want to follow this approach and want to still JSTL (I guess you're using <jsp:useBean />tag) you may initialize a bean property setting the physical folder of your webapp using something like this:

如果您不想遵循这种方法并希望仍然使用 JSTL(我猜您正在使用<jsp:useBean />标签),您可以使用以下内容初始化一个 bean 属性,设置您的 web 应用程序的物理文件夹:

<jsp:useBean id="excelBean" scope="request" class="yourpackage.YourClass" >
    <jsp:setProperty name="physicalPath" value="<%= application.getRealPath("/") %>" />
</jsp:useBean> 

回答by duffymo

This is the wrong approach.

这是错误的做法。

You should be reading that file by putting it in WEB-INF/classes and using getResourceAsStream to get the InputStream from the context path using the file name.

您应该通过将其放入 WEB-INF/classes 并使用 getResourceAsStream 使用文件名从上下文路径中获取 InputStream 来读取该文件。

Try looking at thisexample.

试试看这个例子。

回答by victor hugo

I second duffymo and Martin McNulty, you must use getResourceAsStream and put your Excel file, here it goes the example:

我是第二个 duffymo 和 Martin McNulty,您必须使用 getResourceAsStream 并放置您的 Excel 文件,示例如下:

Your webapp structure is something like this, right?

你的 webapp 结构是这样的,对吧?

- Application Root
 |
 +- WEB-INF
     |
     +- classes/  <--- This is added to CLASSPATH
     |
     +- lib/      <--- Its contents are added to CLASSPATH
     |
     +- web.xml

In this structure your application classpath is conformed by the JAR files located into libfolder and the classesfolder. When you compile using an IDE the files located in your source folder are compiled and the .classfiles are copied in the classesfolder, if the files are not Java files they're just copied in the folder, but still are in the classpath.

在此结构中,您的应用程序类路径由位于lib文件夹和classes文件夹中的 JAR 文件构成。当您使用 IDE 进行编译时,将编译位于源文件夹中的文件,并将.class文件复制到classes文件夹中,如果这些文件不是 Java 文件,则它们只是复制到该文件夹​​中,但仍位于类路径中。

So, being briefly... You can add not-class files in the classpath, like your Excel fileand organise it into packages just like it'd be a class.

所以,简而言之......您可以在类路径中添加非类文件,例如您的 Excel 文件,并将其组织到包中,就像它是一个类一样。

If you put the Excel file in the classpath you'll have the advantage that the file can be accessed independently of your JAR file or WAR file location, just by knowing its location in the classpath.

如果您将 Excel 文件放在类路径中,您将获得的优势是,该文件可以独立于 JAR 文件或 WAR 文件位置进行访问,只需知道它在类路径中的位置即可。

The method Class.getResourceAsStream(String path)provides you access to files into the classpath, just pass the path replacing the dots by slashes, for example:

Class.getResourceAsStream(String path)方法让您可以访问文件到类路径中,只需传递用斜杠替换点的路径,例如:

getClass().getResourceAsStream("/yourpackage/YourExcelFile.xsl");

will provide you an InputStream of the file YourExcelFile.xslthat is inside the package yourpackage.

将为您提供文件的InputStream YourExcelFile.xsl属于包裹里面yourpackage

I tried my best to explain you this but if you have doubts you can check the method documentation.

我已尽力向您解释这一点,但如果您有疑问,可以查看方法文档