Search code examples
jspjava-ee-6servlet-3.0url-mapping

JSP servlet mapping


With introduction of Servlet 3.0 we could map servlets to URL patterns using annotations and ommiting mapping within web.xml.

I wonder if there some intstructions or special tags allowing mapping jsp to URL in page code without declaring servlets in web.xml


Solution

  • There's no facility like that.

    Best what you could do is to hide the JSP in /WEB-INF (so that it can never be requested directly by URL) and just create a servlet which forwards to that JSP and finally map it on the desired URL pattern. It's fairly easy:

    @WebServlet("/foo")
    public class FooServlet extends HttpServlet {
    
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            request.getRequestDispatcher("/WEB-INF/foo.jsp").forward(request, response);
        }
    
    }
    

    This way the JSP in /WEB-INF/foo.jsp is available by http://localhost:8080/context/foo. You could abstract it further to a single servlet for a bunch of JSPs using the front controller pattern.