Servlet Read HTML File Contents Example

April 16, 2014 | Servlets
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

<h2> Getting File contents from the Server </h2>
<form method="get" action="http://localhost:8888/india/HFS">

  Enter HTML File Name <input type="text" name="filename"><br>
  <input type="submit" value="Send Me">
  <input type="reset" value="Clear">

</form>

web.xml entry for Servlet

<servlet>
  <servlet-name>snrao1</servlet-name>
  <servlet-class>HTMLFileSend</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>snrao1</servlet-name>
  <url-pattern>/HFS</url-pattern>
</servlet-mapping>

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("<br>");
      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
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.