How to return an html document from java servlet?

在某一個特定的網址, 想要顯示其他檔案裡的 html 內容.
https://stackoverflow.com/questions/17036130/how-to-return-an-html-document-from-java-servlet


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);    
    }

}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *