简体   繁体   English

如何将文本文件的内容显示到 jsp 页面中

[英]How to display the content of a text file into jsp page

I have a web project.我有一个 web 项目。 After executing the project it will generate a text file that will contain certain result.执行项目后,它将生成一个包含特定结果的文本文件。 And in the final jsp page just contains success report.而在最终的 jsp 页面中只包含成功报告。 But I want to show the content of the text file in to that jsp page.但我想在 jsp 页面中显示文本文件的内容。 What i need to do to achive this?我需要做什么才能实现这一目标?

Thanks.谢谢。 koushik库希克

If the file is saved in public webcontent, then use JSTL <c:import> to display it.如果文件保存在公共 webcontent 中,则使用JSTL <c:import>来显示它。

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<pre><c:import url="file.txt" /></pre>

The <pre> tag is necessary so that newlines are been preserved in HTML output. <pre>标签是必需的,以便在 HTML output 中保留换行符。 Alternatives are adding CSS white-space: pre;替代方案是添加 CSS white-space: pre; to the containing element, or replacing \n with <br/> .到包含元素,或将\n替换为<br/>

If the file is not saved in public webcontent, then create a servlet which gets an InputStream of it by FileInputStream and writes it to the OutputStream of the HttpServletResponse so that you can finally use <c:import> for this.如果文件没有保存在公共 webcontent 中,则创建一个 servlet,它通过FileInputStream获取它的InputStream并将其写入HttpServletResponseOutputStream以便您最终可以使用<c:import>

Scenario 1: you need to open the txt file, read content & write it to the outputstream.场景 1:您需要打开 txt 文件,读取内容并将其写入输出流。

BufferedReader br = new InputStreamReader(new FileInputStream("<<file>>"));

String line = br.readLine();
while(line!=null){
 out.println(line);
 line = br.readLine();
}

this reads the file & write the contents to the jsp这将读取文件并将内容写入 jsp

this needs to be done in the JSP...这需要在 JSP 中完成...

its also advisable to move this piece of code to a support class & use that class to retrieve the file contents.还建议将这段代码移动到支持 class 并使用该 class 来检索文件内容。

Is the text file generated by your web application as a result of a user request?您的 web 应用程序生成的文本文件是用户请求的结果吗? If so, then your action bean (or servlet) which triggered the generation of the file must have access to its content.如果是这样,那么触发文件生成的动作 bean(或 servlet)必须有权访问其内容。 Couldn't you set the file content as an action bean property (or servlet parameter), in which case the JSP would have access to it and can then display it?您不能将文件内容设置为操作 bean 属性(或 servlet 参数),在这种情况下,JSP 可以访问它并显示它吗?

You can use JSTL import tag.您可以使用 JSTL导入标签。 It imports the content of a URL-based resource.它导入基于 URL 的资源的内容。

<c:import var="data" 
          url="http://www.example.com/file.txt"
          scope="session"/>

<c:out value="${data}"/>

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

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