2014-01-30 44 views
2

是否可以在運行時動態添加URL模式到Servlet?例如,當Servlet啓動時,掃描文件夾中的註釋,然後將這些url模式注入到servlet中?Java - 向Servlet動態添加URL模式

  • 提供更清晰 -

在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 
+0

也許我誤解了。你想在啓動時或之後使用嗎? –

+0

啓動時確定。例如,在servlet的init()函數中。 – bluedevil2k

+0

目的是什麼?你確定使用簡單的控制器模式不會更好嗎? –

回答

7

我不知道我理解你的最終目標,但這是一個可能的解決方案。

使用Servlet 3.0,實現ServletContainerInitializer接口。作爲javadoc的說

此接口的實現必須由一個JAR文件所在的META-INF/services目錄內 資源並命名爲 這個接口的完全限定類名

在被宣佈爲它註冊了onStartup(..)方法,您將有權訪問Web應用程序的類路徑中的所有類。

逐一掃描。如果某個類在您想要的包中,並且它包含您正在查找的註釋,則對其進行處理並將該URL模式存儲在一個集合中。

掃描完成後,您可以使用提供的ServletContext註冊Servlet實例/類,並使用給定的ServletRegistration.Dynamic對象註冊URL模式。

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

如果您需要它們,還有許多其他配置選項。

+0

我同意你的解決方案,但只能使用Servlet3 .. – Koitoer

+0

@Koitoer是的,我已經添加了一個說明。謝謝。 –