Search code examples
javatomcatservletsjakarta-ee

Can i make a Java Servlet unaccessible from outside?


Similiar to this question, but I want a regular servlet to be only accessible through the RequestDispatcher.

For example, I have a servlet that is mapped to /hiddenUrl. This should happen:

//forwards successfully
request.getRequestDispatcher(contextPath + "/hiddenUrl").forward(request,response);

//404 not found
response.sendRedirect(contextPath + "/hiddenUrl")  

Just like a JSP that is moved inside WEB-INF directory. Is it possible?


Solution

  • A servlet container will never directly serve a request starting with /META-INF/ or /WEB-INF/ (see chapter 10.5 of the specification):

    A special directory exists within the application hierarchy named WEB-INF. This directory contains all things related to the application that aren’t in the document root of the application. Most of the WEB-INF node is not part of the public document tree of the application. Except for static resources and JSPs packaged in the META-INF/resources of a JAR file that resides in the WEB-INF/lib directory, no other files contained in the WEB-INF directory may be served directly to a client by the container.

    Therefore a servlet mapped to /WEB-INF/something will be visible to other servlets and JSPs, but not directly to the user.