您可以从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");另外,还要注意的是,一个
RequestDispatcher可以从两个检索
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); }}


