Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java Servlets
Expertise: Beginner
Oct 15, 1999



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Simple HTML Display

How can I have my servlet display an HTML file, located on the server, on the client's browser?

The HttpServlet class makes it very simple to send and receive information to and from a Web browser. HttpServlet overrides the Servlet service method and converts its arguments to HttpServletRequest and HttpServletResponse objects.

These are dispatched to an appropriate "do" method that you override and implement. HTTP GET requests are dispatched to the doGet method, which you would need to implement in order to send an HTML file to a browser.

To transmit a file, you need to open it and copy its contents to a Writer obtained from the ServletResponse using getWriter(). Before obtaining the writer, you need to set the content type of the data to an appropriate MIME type, in this particular case text/html. The accompanying code example demonstrates how to do this.

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

public class SimpleServlet extends HttpServlet {

 protected void doGet(HttpServletRequest request,
                      HttpServletResponse response)
   throws ServletException, IOException
   char[] buffer = new char[1024];
   int bytesRead;
   PrintWriter writer;
   Reader reader;

   writer = response.getWriter();
   // The filename will be interpreted relative to the current working
   // directory of the Servlet engine, so you would probably want to use
   // an absolute path.
   reader = new BufferedReader(new FileReader("foo.html"));

   while((bytesRead = reader.read(buffer)) != -1)
     writer.write(buffer, 0, bytesRead);

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date