從一個servlet跳轉到另一個webapp的某個地址處理請求
阿新 • • 發佈:2019-02-05
例如:使用者下單servlet跳轉至另一個應用倉庫管理的servlet中核對商品資訊,再確認後返回使用者請求。
<span style="font-size:14px;">public class test extends HttpServlet{ private static final long serialVersionUID = -37232222805167898L; @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{ //++++++需要把請求轉移到另外一個Web App中的某個地址,可以按以下做法+++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // 獲得另外一個Web App的ServletConext物件(currentServletContext.getContext(uripath)) ServletContext context =getServletContext().getContext("http://localhost:8080/apache-tomcat-7.0.62/webapps/examples"); // 呼叫ServletContext.getRequestDispatcher(String url)方法,forward寫在一起可以 // 相對於webapp根目錄的絕對路徑 context.getRequestDispatcher("/otherwebapp.jsp").forward(req,resp); // 相對於context,也就是webapp根目錄的相對路徑 context.getRequestDispatcher("otherwebapp.jsp").forward(req,resp); } </span>