如何从java servlet返回一个html文档?

这可以返回一个字符串:

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中有这个

  Monkey com.self.edu.MonkeyServlet   Monkey /monkey  

还有什么我可以放在那里所以它只返回一个文件,如…

  Monkey blot.html  

您可以从Servlet本身打印出HTML (不建议使用)

 PrintWriter out = response.getWriter(); out.println(""); out.println("

My HTML Body

"); out.println("");

或者, 调度到现有资源(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"); 

另请注意,可以从ServletRequestServletContext检索RequestDispatcher ,区别在于前者也可以采用相对路径

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