You either print out the HTML from the Servlet itself (deprecated)
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>My HTML Body</h1>");
out.println("</body></html>");
or, dispatch to an existing resource (servlet, jsp etc.) (called forwarding to a view) (preferred)
RequestDispatcher view = request.getRequestDispatcher("html/mypage.html");
view.forward(request, response);
The existing resource that you need your current HTTP request to get forwarded to does not need to be special in any way i.e. it's written just like any other Servlet or JSP; the container handles the forwarding part seamlessly.
Just make sure you provide the correct path to the resource. For example, for a servlet the RequestDispatcher
would need the correct URL pattern (as specified in your web.xml)
RequestDispatcher view = request.getRequestDispatcher("/url/pattern/of/servlet");
Also, note that the a RequestDispatcher
can be retrieved from both ServletRequest
and ServletContext
with the difference that the former can take a relative path as well.
Reference:
http://docs.oracle.com/javaee/5/api/javax/servlet/RequestDispatcher.html
Sample Code
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);
}
}