Java - Dynamically Adding URL Pattern to a Servlet

2020-07-27 04:45发布

问题:

Is it possible to add a URL pattern to a Servlet dynamically at runtime? For example, when the Servlet starts up, scan a folder for annotations, and then inject those url patterns into the servlet?

  • to provide more clarity -

In the Servlet's init file, I want to do this (pseudo-code)

// scan all the files in the package my.project.services
// find all the classes with the Annotation @Service
// read those annotations, find the url patterns in them, and insert them into the servlet

回答1:

I'm not sure I understand your end goal, but here's a possible solution.

With Servlet 3.0, implement the ServletContainerInitializer interface. Register it as the javadoc says

Implementations of this interface must be declared by a JAR file resource located inside the META-INF/services directory and named for the fully qualified class name of this interface

In its onStartup(..) method, you will have access to all the classes on your web application's classpath.

Scan them one by one. If a class is in the package you want and it has the annotation you are looking for, process it and store the URL pattern in a collection.

When the scan is done, you can register Servlet instances/classes with the provided ServletContext and register URL patterns with the given ServletRegistration.Dynamic object.

ServletRegistration.Dynamic registration = servletContext.addServlet("myServlet", new MyServlet());
registration.addMapping(yourCollectionAsAStringArray);

You have many other configuration options as well if you need them.