2

How to read data from a text file using JSP and that to retrieval should take place without using any java code in JSP and the text file should not be placed under WEB-INF?

lalith
  • 21
  • 2
  • Use a servlet, and put your Java code in the servlet. Once the file is read, the servlet can use the request dispatcher to forward to a JSP page in order to generate HTML. That's the basic architecture of MVC. – JB Nizet Apr 01 '15 at 06:08
  • [this link will help you][1] http://stackoverflow.com/questions/4533018/how-to-read-a-text-file-from-server-using-javascript – anand kulkarni Apr 01 '15 at 06:30
  • thnq fr ur ans JB , but we should not use any java code but we have to retrieve it! is it posiible ?my requirement is :there is jsp page and text file and i have to retrieve data from text file using jsp.there should not be any servlets. – lalith Apr 01 '15 at 06:42
  • You can write java code in `scriptlet`. – vivekpansara Apr 01 '15 at 11:21

1 Answers1

2

HTML5 introduced the JavaScript object FileReader. It is now supported by all major browsers and no additional libraries are needed. After you instantiate the new object, you can read the file in as an ArrayBuffer, BinaryString, DataURL, or Text. Here is an example:

document.getElementById('file').addEventListener('change', function(e) {

    var file = document.getElementById('file').files[0];

    var reader = new FileReader();
    reader.readAsText(file);
    reader.onload = function(e) {
        document.getElementById('results').innerText = reader.result;
    }
});
<input id="file" type="file">
<div id="results"></div>

I also put a working example on JSFiddle

Here is the link to the documentation.

Shaggy
  • 1,444
  • 1
  • 23
  • 34