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