如何从java servlet返回html文档?

2022-09-02 02:37:29

这用于返回一个字符串:

import javax.servlet.http.*;
@SuppressWarnings("serial")
public class MonkeyServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {

        resp.setContentType("text/plain");
        resp.getWriter().println("got this far");

    }

}

但是我无法让它返回html文档。这不起作用:

import javax.servlet.http.*;
@SuppressWarnings("serial")
public class BlotServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {

        resp.setContentType("text/html");
        resp.getWriter().println("html/mypage.html");

    }

}

很抱歉成为菜鸟!

编辑:

我已经在单独的文档中拥有html。所以我需要返回文档,或者以某种方式阅读/解析它,所以我不只是重新输入所有的html...

编辑:

我的网络中有这个.xml

<servlet> 
    <servlet-name>Monkey</servlet-name> 
    <servlet-class>com.self.edu.MonkeyServlet</servlet-class> 
</servlet> 
<servlet-mapping> 
    <servlet-name>Monkey</servlet-name> 
    <url-pattern>/monkey</url-pattern> 
</servlet-mapping>

有没有其他东西我可以放在那里,所以它只是返回一个文件,比如......

<servlet-mapping> 
    <servlet-name>Monkey</servlet-name> 
    <file-to-return>blot.html</file-to-return> 
</servlet-mapping>

答案 1

您可以从 Servlet 本身打印出 HTML(已弃用)

PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>My HTML Body</h1>");
out.println("</body></html>");

或者,调度到现有资源(servlet,jsp等)(称为转发到视图)(首选)

RequestDispatcher view = request.getRequestDispatcher("html/mypage.html");
view.forward(request, response);

您需要将当前HTTP请求转发到的现有资源不需要以任何方式特殊,即它就像任何其他Servlet或JSP一样编写;容器无缝处理转发部分。

只需确保提供资源的正确路径即可。例如,对于 servlet,将需要正确的 URL 模式(如 web 中指定的.xml)RequestDispatcher

RequestDispatcher view = request.getRequestDispatcher("/url/pattern/of/servlet");

另外,请注意,可以从两者中检索a,并且不同之处在于前者也可以采用相对路径RequestDispatcherServletRequestServletContext

参考资料:
http://docs.oracle.com/javaee/5/api/javax/servlet/RequestDispatcher.html

示例代码

public class BlotServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws IOException {
        // we do not set content type, headers, cookies etc.
        // resp.setContentType("text/html"); // while redirecting as
        // it would most likely result in an IllegalStateException

        // "/" is relative to the context root (your web-app name)
        RequestDispatcher view = req.getRequestDispatcher("/path/to/file.html");
        // don't add your web-app name to the path

        view.forward(req, resp);    
    }

}

答案 2

推荐