简体   繁体   中英

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

I have a web project. 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. But I want to show the content of the text file in to that jsp page. 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.

<%@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. Alternatives are adding CSS white-space: pre; to the containing element, or replacing \n with <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.

Scenario 1: you need to open the txt file, read content & write it to the outputstream.

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

this needs to be done in the JSP...

its also advisable to move this piece of code to a support class & use that class to retrieve the file contents.

Is the text file generated by your web application as a result of a user request? If so, then your action bean (or servlet) which triggered the generation of the file must have access to its content. 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?

You can use JSTL import tag. It imports the content of a URL-based resource.

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

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

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