Return HTML / XHTML file from servlet

I saw examples of servlets, they are 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: can I return an HTML page instead of code? I mean, something like this:

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

Thanks!!!;)

+4
source share
1 answer

There are several different ways to do this:

  • Move the servlet to the path where the HTML file is located. Sort of:

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

  • Send a redirect to the URL where the HTML is located. Sort of:

    response.sendRedirect("something.html");

  • Read the contents of the HTML file, and then write the contents of the HTML file to the PrintWriter servlet.

+8
source

Source: https://habr.com/ru/post/1484840/


All Articles