ServletRequest.getRequestDispatcher
getRequestDispatcher
publicRequestDispatcher getRequestDispatcher(java.lang.String path) |
这是javax.servlet.ServletRequest下的一个public成员函数。
(Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. A RequestDispatcher object can be used to forward a request to the resource or to include the resource in a response. The resource can be dynamic or static. ) |
episode:
它返回一个RequestDispatcher对象,在JDK的文档里是这样定义RequestDispatcher对象的:[Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server.]
RequestDispatcher对象从客户端获取请求request,并把它们传递给服务器上的servlet,html或jsp。
它的方法很easy,只有两个:
1.voidforward(ServletRequestrequest,ServletResponseresponse) |
一看就明白,这是用来传递request的,可以一个Servlet接收request请求,另一个Servlet用这个request请求来产生response。request传递的请求,response是客户端返回的信息。forward要在response到达客户端之前调用,也就是 before response body output has been flushed。如果不是的话,它会报出异常。
例:
request.getRequestDispatcher("smserror.jsp").forward(request,response); |
2.voidinclude(ServletRequestrequest,ServletResponseresponse) |
Includes the content of a resource (servlet, JSP page, HTML file) in the response.
The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored.这个是用来记录保留request和response,以后不能再修改response里表示状态的信息了
getRequestDispatcher(String)可以得到一个RequestDispatcher对象,那我们就可以用它来动态的调用我们想要的调用的Servlet,jsp等;而参数String,就是那个你要调用的Servlet或JSP的名称,它可以是相对路径(如前例),也可以是绝对路径,如果你在前面加上“/”。