Java - 动态地将URL模式添加到Servlet

blu*_*l2k 2 java servlets servlet-3.0

是否可以在运行时动态地向Servlet添加URL模式?例如,当Servlet启动时,扫描文件夹中的注释,然后将这些url模式注入到servlet中?

  • 提供更清晰 -

在Servlet的init文件中,我想这样做(伪代码)

// 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
Run Code Online (Sandbox Code Playgroud)

Sot*_*lis 7

我不确定我理解你的最终目标,但这是一个可能的解决方案.

使用Servlet 3.0,实现ServletContainerInitializer接口.注册为javadoc说

此接口的实现必须由位于META-INF/services目录内的JAR文件资源声明,并以此接口的完全限定类名命名

在其onStartup(..)方法中,您将可以访问Web应用程序的类路径中的所有类.

逐个扫描它们.如果一个类在你想要的包中,并且它有你正在寻找的注释,则处理它并将URL模式存储在一个集合中.

扫描完成后,您可以Servlet使用提供的ServletContext注册URL模式和给定ServletRegistration.Dynamic对象注册实例/类.

ServletRegistration.Dynamic registration = servletContext.addServlet("myServlet", new MyServlet());
registration.addMapping(yourCollectionAsAStringArray);
Run Code Online (Sandbox Code Playgroud)

如果需要,还有许多其他配置选项.