Servlet中有兩種方式獲得轉(zhuǎn)發(fā)對象(RequestDispatcher):一種是通過HttpServletRequest的getRequestDispatcher()方法獲得,一種是通過ServletContext的getRequestDispatcher()方法獲得;
重定向的方法只有一種:HttpServletResponse的sendRedirect()方法。
這三個方法的參數(shù)都是一個URL形式的字符串,但在使用相對路徑或絕對路徑上有所區(qū)別。
★ HttpServletResponse.sendRedirect(String)
參數(shù)可以指定為相對路徑、絕對路徑或其它Web應(yīng)用。
假設(shè)通過http://localhost/myApp/cool/bar.do請求到達該方法所屬的Servlet。
相對路徑:response.sendRedirect("foo/stuff.do")
容器相對于原來請求URL的目錄加參數(shù)來生成完整的URL——http://localhost/myApp/cool/foo/stuff.do。
絕對路徑:response.sendRedirect("/foo/stuff.do")
容器相對于Web應(yīng)用本身加參數(shù)建立完整的URL——http://localhost/foo/stuff.do。
其它Web應(yīng)用:response.sendRedirect("http://www.iteye.com")
容器直接定向到該URL。
★ HttpServletRequest.getRequestDispatcher(String)
參數(shù)可以指定為相對路徑或絕對路徑。
相對路徑情況下生成的完整URL與重定向方法相同。
絕對路徑與重定向不同,容器將相對于Web應(yīng)用的根目錄加參數(shù)生成完整的URL,即:
request.getRequestDispatcher("/foo/stuff.do")生成的URL是http://localhost/myApp/foo/stuff.do。
★ ServletContext.getRequestDispatcher(String)
參數(shù)只能指定為絕對路徑,生成的完整URL與HttpServletRequest.getRequestDispatcher(String)相同。