Java如何获取另一个应用程序的ServletContext?
该ServletContext.getContext(Stringuripath)使我们部署在同一个应用程序服务器上的其他Web应用程序的访问servlet上下文。需要添加配置以启用此功能。
在下面的示例中,我们将从request当前应用程序转发到/otherapp/hello.jsp页面。我们request在当前应用程序的object属性中放置一个字符串,并将其显示在hello.jsp页面中。
package org.nhooo.example.servlet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns = {"/context"})
public class GetAnotherContextServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取同一Servlet上另一个应用程序的ServletContext
//容器。这使我们可以将请求转发到另一个应用程序
//在同一应用程序服务器上。
ServletContext ctx = request.getServletContext().getContext("/otherapp");
//设置一个请求属性并转发到另一个的hello.jsp页面
//上下文。
request.setAttribute("MESSAGE", "Hello There!");
RequestDispatcher dispatcher = ctx.getRequestDispatcher("/hello.jsp");
dispatcher.forward(request, response);
}
}要在Tomcat中启用此功能,我们需要crossContext通过将值设置为来启用属性true,默认值为false。更新server.xml文件以添加以下配置。
... <Context path="/webapp" debug="0" reloadable="true" crossContext="true"/> ...