简体   繁体   中英

Cannot read file data from jsp file on remote server

My dynamic web project has following structure.

WebContent/WEB-INF/jsps/index.jsp. I'm trying to access file.txt from my jsp file and display content from that file. file.txt is in WebContent/resources folder.

I'm using,

String jspPath = session.getServletContext().getRealPath("/resources"); jspPath = jspPath.replace("\\\\", "/"); String fileName = "/file.txt"; String txtFilePath = jspPath + fileName;

After opening file, code to display content.

It is working on localhost but when I upload it online, it is not displaying content from text file on jsp page.

I'm not getting why it is not working, I think filepath might be a problem because it was throwing FileNotFoundException but I fixed it by making few changes. Now it is not displaying content. Can someone please help? I'm uisng openshift deployment platform for .war file.

Actually , your above JSP page will never be executed because it is in the WEB-INF folder which is not accessible for the end users, so make sure to put your JSP's out of WEB-INF.
For reading the file , you can load and print the file in simpler way:

<%@page import="java.io.*"%>
<% 
InputStream in=config.getServletContext().getResourceAsStream("/resources/hello.txt");
int ch;
while((ch=in.read())!=-1){
    out.print((char)ch);
}
in.close();
%>

Since the above method of calling getRealPath will not work with application servers using virtual file-systems like JBoss.

Note: for better performance , you can use other methods of reading files to include(eg Buffering and caching), but this will be out of the scope of this question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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