Returning an HTML/XHTML file from servlet

2019-05-07 14:10发布

问题:

I've seen servlets examples, they're something like this:

 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">");
        ...
    }

My question is, instead of the code, can I return an HTML page? I mean, something like this:

 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            PrintWriter out = response.getWriter();

            SHOW(FILE.HTML);

        }

Thanks!!! ;)

回答1:

There are a few different ways you could do this:

  1. Forward the servlet to the path where the HTML file is located. Something like:

    RequestDispatcher rd = request.getRequestDispatcher("something.html"); rd.forward(request, response);

  2. Send a redirect to the URL where the HTML is located. Something like:

    response.sendRedirect("something.html");

  3. Read in the contents of the HTML file and then write out the contents of the HTML file to the servlet's PrintWriter.