java 从 servlet 返回 HTML/XHTML 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16964126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 00:32:43  来源:igfitidea点击:

Returning an HTML/XHTML file from servlet

javahtmlservletsxhtml

提问by dak

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

我看过 servlets 的例子,它们是这样的:

 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:

我的问题是,我可以返回 HTML 页面而不是代码吗?我的意思是,像这样:

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

            SHOW(FILE.HTML);

        }

Thanks!!! ;)

谢谢!!!;)

回答by worpet

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.

  1. 将 servlet 转发到 HTML 文件所在的路径。就像是:

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

  2. 将重定向发送到 HTML 所在的 URL。就像是:

    response.sendRedirect("something.html");

  3. 读入 HTML 文件的内容,然后将 HTML 文件的内容写出到 servlet 的 PrintWriter。