Java - Dynamically Adding URL Pattern to a Servlet

大城市里の小女人 提交于 2019-12-06 10:25:33

问题


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.



来源:https://stackoverflow.com/questions/21461797/java-dynamically-adding-url-pattern-to-a-servlet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!