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

Getting File contents from the Server

Enter HTML File Name

web.xml entry for Servlet


  snrao1
  HTMLFileSend



  snrao1
  /HFS

Servlet File: HTMLFileSend.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class HTMLFileSend extends HttpServlet   
{
  public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException  
  {
    res.setContentType("text/html");
    PrintWriter pw = res.getWriter();

    String name = req.getParameter("filename");

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

    int k;
    char ch;

    while( (k = fr.read()) != -1 )
    {
      ch = (char) k;

      if(k == 13) 		 // 13 is ASCII value of new line character
        pw.print("
"); else if(ch == '<') pw.print("<"); else if(ch == '>') pw.print(">"); else pw.print(ch); } fr.close(); pw.close(); } }

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 Comment

Your email address will not be published.