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

女生的网名这么多〃 提交于 2019-12-22 11:03:57

问题


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.

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.

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

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?

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());                
        }
    }
}

回答1:


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

context.getRealPath("/");

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

getServletConfig().getServletContext();

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

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.




回答2:


In a basic JSP/Servlet app you'd have a backing servlet which will do almost all the logic in your program, push the model into a request and then redirect the user to a JSP page that will pull the 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

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:

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



回答3:


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.

Try looking at this example.




回答4:


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.

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

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

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



回答5:


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

Your webapp structure is something like this, right?

- 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 lib folder and the classes folder. When you compile using an IDE the files located in your source folder are compiled and the .class files are copied in the classes folder, if the files are not Java files they're just copied in the folder, but still are in the classpath.

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

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.

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:

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

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

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



来源:https://stackoverflow.com/questions/918396/how-to-get-the-path-of-servers-folder-inside-java-program-j2ee-jstl

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!