Returning an HTML/XHTML file from servlet

心已入冬 提交于 2019-12-07 12:06:35

问题


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.



来源:https://stackoverflow.com/questions/16964126/returning-an-html-xhtml-file-from-servlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!