Servlet Read HTML File Contents Example

Servlet Read HTML File Contents Example

Earlier we did a program where client requested for a text file; but the case now is with HTML file. Now it is HTML file with Servlet read html file.

If the user sends a request for HTML file, when it comes to the browser, it is interpreted and output of the HTML file is obtained and not the HTML contents as it is. To overcome this, it must be read angle brackets of the HTML file separately.

In case the file user wanted is a HTML file, the Servlet file should be changed slightly as follows where HTML angle brackets should be read differently.

Example on Servlet read html file

Client HTMl File: HTMLFileSend.html

web.xml entry for Servlet

Servlet File:

In the earlier text file reading, We used BufferedReader to read a line at a time. Now, here FileReader is used to read character by character.

FileReader fr = new FileReader("C:/" + name);

It is assumed that the file wanted by the client is existing in C drive.

if(k == 13)

If the character read from the file is 13, send a <BR> to client browser. 13 is the ASCII value of new line (obtained with enter key).

If the character read is < angle bracket, send lt; prefixed by & and similarly with > also.

Finally if not all, send the character itself to client (else condition is executed).

Servlet read html file

Servlet read html file
Output screens with client request and server response of Servlet read html file

There is another way of reading HTML file contents and sent to client which is very easier than this and is explained in response.getOutputStream() Example.

2 thoughts on “Servlet Read HTML File Contents Example

Leave a Reply

Your email address will not be published. Required fields are marked *