更新时间:2023-12-04 14:11:04
你 print 从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一样编写;容器无缝地处理转发部分。
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.
只需确保提供资源的正确路径。例如,对于servlet, RequestDispatcher
将需要正确的URL模式(在web.xml中指定)
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");
另外,请注意a RequestDispatcher
可以从 ServletRequest
和 ServletContext
中检索,区别在于前者可以采用 相对路径 。
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.
参考:
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);
}
}