简体   繁体   English

无法从远程服务器上的jsp文件读取文件数据

[英]Cannot read file data from jsp file on remote server

My dynamic web project has following structure. 我的动态Web项目具有以下结构。

WebContent/WEB-INF/jsps/index.jsp. WebContent / WEB-INF / jsps / index.jsp。 I'm trying to access file.txt from my jsp file and display content from that file. 我正在尝试从我的jsp文件访问file.txt并显示该文件中的内容。 file.txt is in WebContent/resources folder. file.txt在WebContent / resources文件夹中。

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. 它可以在localhost上运行,但是当我在线上传它时,它不在jsp页面上显示文本文件中的内容。

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. 我不明白为什么它不起作用,我认为文件路径可能是一个问题,因为它引发了FileNotFoundException,但我通过进行少量更改来解决了该问题。 Now it is not displaying content. 现在它不显示内容。 Can someone please help? 有人可以帮忙吗? I'm uisng openshift deployment platform for .war file. 我正在使用.war文件的openshift部署平台。

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. 实际上,上面的JSP页面将永远不会执行,因为它位于最终用户无法访问的WEB-INF文件夹中,因此请确保将JSP放在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. 由于上述调用getRealPath方法不适用于使用虚拟文件系统(如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. 注意:为了获得更好的性能,您可以使用其他方法读取文件以包含(例如,缓冲和缓存),但这不在此问题的范围内。

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

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