servletscontext.xmltomcat10

getServletContext()#getContext return null even after crossContext defined as true


In the context /inbox deployed on tomcat10, I have added the file META-INF/context.xml with this content:

<?xml version="1.0" encoding="UTF-8" ?>
<Context crossContext="true" />

but when I try forward to another context, with:

getServletContext().getContext("/auth").getRequestDispatcher("/login").forward(request, response);

I got the error:

Cannot invoke "jakarta.servlet.ServletContext.getRequestDispatcher(String)" because the return value of "jakarta.servlet.ServletContext.getContext(String)" is null

What I am missing here?

the call above is used in this servlet from /inbox:

@WebServlet(name = "Home", urlPatterns = "/home")
public class Home extends HttpServlet {
    protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    ...
    }
}

I also have tried the strings /../auth and /../../auth for the context, but the same error occurs.


Solution

  • The META-INF folder containing the context.xml needs to be the one in the root of the WAR file, not the one in WEB-INF/classes folder. This is simply because it is as being a server-specific configuration file not supposed to be available in the classpath of the web application. In case of a default Maven project it's expected that the source file path is src/main/webapp/META-INF/context.xml and thus not e.g. src/main/resources/META-INF/context.xml.