2013-02-08 104 views
9

我正在嘗試將spring注入到servlet過濾器中。過濾器是引用的jar文件的一部分。所以。我不能把它改成攔截器。在我的插件項目在Servlet過濾器中注入彈簧

<filter> 
    <filter-name>CustomFilter</filter-name>  
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
    <init-param>  
     <param-name>someinitparam</param-name>  
     <param-value>value to it</param-value>  
    </init-param> 
</filter> 
<filter-mapping> 
    <filter-name>CustomFilter</filter-name> 
    <url-pattern>/mywebservices/*</url-pattern> 
</filter-mapping> 

在spring.xml的web.xml中我會用這樣的

<bean id="CustomFilter" class="com.abc.CustomFilter"></bean> 

有一些過濾器在spring.xml已配置爲

<bean id="filterChainProxy" class="org.acegisecurity.util.FilterChainProxy"> 
    <property name="filterInvocationDefinitionSource"> 
     <value> 
      CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON 
      PATTERN_TYPE_APACHE_ANT 
      /mywebservices/*=some existing filters 
     </value>    
    </property> 
</bean> 

因爲我已經在web.xml中指定了我的url模式,我是否需要再次在filterChainProxy中添加爲

/mywebservices/**=CustomFilter, some existing filters 

它會工作嗎。

請建議。

+0

將它的工作

<filter> <filter-name>CustomFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>CustomFilter</filter-name> <url-pattern>/mywebservices/*</url-pattern> </filter-mapping> 

,然後注入屬性可以配置過濾器?你有沒有嘗試過? – TheWhiteRabbit

+0

嗯..聽起來很棘手。 Spring依賴注入通常是在Spring上下文創建的bean上完成的,而過濾器是由java ee服務器本身創建的。也許你可以做的是 - 如果你可以確定在你創建Filter類的時候spring context已經準備好了 - 試着以某種方式獲得對它的引用。順便說一句,你能告訴我們更多關於你的應用程序的信息 - 做你使用Spring MVC?如果是這樣,也許你不需要使用servlet過濾器 – gerrytan

+0

@TechExchange。我已經嘗試過,但它對我的應用程序造成嚴重錯誤。 – Patan

回答

0

我認爲你不能在Spring上下文外部注入bean,並且你的servlet過濾器不在spring上下文中。如果你想在上下文中使用過濾器,那麼我建議去春季網頁攔截器。這些攔截器在春天的上下文中,你可以利用這些攔截器的彈簧容器功能。

+1

Spring Security使用Spring應用程序上下文中定義的許多過濾器。這就是'DelegatingFilterProxy'的用途。 –

+0

這個答案根本不正確 –

14

像你在web.xml的確在spring.xml

<bean id="CustomFilter" class="com.abc.CustomFilter"> 
    <property name="someParameter"> 
     <value>some value</value> 
    </property> 
</bean> 
+0

謝謝你的回答。我們是否可以將servlet過濾器的in-it參數註冊爲元素的屬性,或者我們是否必須在web.xml中的元素中指定它。 – Patan

+0

還因爲我已經在web.xml中將url模式指定爲/mywebservices/*。我是否需要將其作爲值添加到bean中的/ myservice/**中,並使用id filterChainProxy。請幫助 – Patan

+0

FilterChainProxy是可選的,用於精確控制執行哪些過濾器。通常你不需要明確地定義它。如果出於其他原因,如果您還在其中添加了過濾器,那麼您沒有問題 – ckoidl