Dynamic context registration
In the preceding servlets and web components section, we saw how to declare a servlet and its context path through the @WebServlet
annotation or through the web.xml
descriptor file. The same thing can be done dynamically at the programming level. As an example, we will write a servlet without context path and a context listener that dynamically registers the servlet. Here's the servlet:
public class RegistrationDynamicServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().print("dynamic GET"); } }
This is the context listener:
@WebListener public class RegistrationContextListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent sce) { ServletRegistration.Dynamic registration = sce.getServletContext().addServlet("dynamic",RegistrationDynamicServlet.class); registration.addMapping...