Simple HTML Display

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 receiveinformation to and from a Web browser. HttpServlet overrides theServlet service method and converts its arguments toHttpServletRequest and HttpServletResponse objects.

These are dispatched to an appropriate “do” method that you override andimplement. 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 contentsto a Writer obtained from the ServletResponse using getWriter().Before obtaining the writer, you need to set the content type of thedata to an appropriate MIME type, in this particular case text/html.The accompanying code example demonstrates how to do this.

import*;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 = != -1)     writer.write(buffer, 0, bytesRead);   reader.close();  }}


Share the Post: