2013-03-25 43 views
0

你好,我是Spring的新手。 我正在開發一個Spring Web Api,並且在使用正則表達式解析URL時遇到問題。我已經看過以下職位:Spring Web Api,解析URLS

http://stackoverflow.com/questions/7841770/optional-path-variables-in-spring-mvc-requestmapping-uritemplate 
http://stackoverflow.com/questions/12516969/spring-mvc-getting-pathvariables-containing-dots-and-slashes 
http://stackoverflow.com/questions/8998419/requestmapping-annotation-in-spring-mvc 

,但我還沒有找到一個尚未解決我的問題。 我希望我的所有請求都可以映射到單個方法,URL的長度可以變化,參數的數量也可以變化。我想捕捉整個URL與可變pathValue,而不是直到斜線/:

@RequestMapping(值=「{} pathValue」,方法= RequestMethod.GET)

所有的正則表達式,我有在Spring中捕獲斜槓(/....../)的內容進行了測試,並且不考慮de剩餘的URL。

重點是,我想解析一個單一的方法中的網址,這意味着所有請求都映射到該方法。 有什麼辦法可以在Spring中實現這一點?

非常感謝您的幫助和建議。

回答

0

如果你真的想將所有的請求分派給一個處理程序,那麼你根本不需要擁有spring方法分派器。

相反,你可以有自己的請求處理程序

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> 
    <property name="urlMap"> 
     <map> 
       <entry key="/**" value="myCatchAllResourceHandler" /> 
     </map> 
    </property> 
    <property name="order" value="100000" />  
</bean> 

<bean id="myCatchAllResourceHandler" name="myCatchAllResourceHandler" 
     class="MyCatchAllResourceHandler"> 
</bean> 

你必須實現自己的請求處理程序

public class MyCatchAllResourceHandler extends HttpRequestHandler() { 

    /** 
    * Process the given request, generating a response. 
    * @param request current HTTP request 
    * @param response current HTTP response 
    * @throws ServletException in case of general errors 
    * @throws IOException in case of I/O errors 
    */ 
    void handleRequest(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException; 
     System.out.println("I get invoked");  
    } 
} 

但說實話,這幾乎是像投擲所有的Spring MVC了!

+0

謝謝你的迴應。但是,如果我使用Spring功能,我怎樣才能讓Spring過濾不正確的URLS並顯示一個自定義錯誤頁面,因爲不正確的URLS的數量比正確的大。有沒有辦法映射不正確的URL?謝謝。 – amartin 2013-03-25 10:41:03

+0

你的意思是你想自定義「資源未找到」頁面? – Ralph 2013-03-25 11:10:17

+0

我想過濾無效的URL,例如:portal/customer/item和門戶/推薦/用戶/產品/ book是有效的URLS,但門戶/推薦不是有效的URL。我想有一個方法來確定一個URL是否正確。 – amartin 2013-03-25 11:58:54