21

这可以返回一个字符串:

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 ......

编辑:

我的 web.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>
4

1 回答 1

54

您可以从 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,RequestDispatcher需要正确的 URL 模式(在 web.xml 中指定)

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

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

参考:
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);    
    }

}
于 2013-06-11T03:41:36.600 回答