Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


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

Simple HTML Display

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

Answer:
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;

   response.setContentType("text/html");
   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);

   reader.close();
  }
}
DevX Pro
 
Comment and Contribute

 

 

 

 

 


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

 

 

Sitemap