2011-08-05 82 views
1

我正在開發一個使用Spring MVC框架(v3)的web應用程序。Spring MVC控制器配置 - 混合註釋和XML @PathVariable

目前,我有幾個控制器類中定義的 - 我創造了他們通過擴展的MultiActionController,然後在我的Web MVC框架XML配置定義的bean和URL映射:

QuestionController.java:

public class QuestionController extends MultiActionController implements InitializingBean 
{ 

webmvc-config.xml中

<bean id="questionController" class="com.tmm.enterprise.microblog.controller.QuestionController"></bean> 
... 
    <bean id="fullHandlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> 
     <property name="alwaysUseFullPath" value="true" /> 
     <property name="mappings"> 
      <props> 
       <prop key="/question/**">questionController</prop> 
      </props> 
     </property> 
    </bean> 

這工作得很好,我定義在我的控制器匹配的URL方法被調用和對一切g工作正常(例如,我有一個list(..)方法,當我瀏覽到/question/list時,它會正確執行)。

然而,對於這個特定的控制器我想利用Spring中的@PathVariable選項允許可變的網址(例如,我要一個details(..)方法,當我打電話/question/detail/9999 - 在9999是指在執行方法的問題ID )。我曾嘗試使用此如下:

QuestionController.java:

@RequestMapping("/detail/{questionId}") 
public ModelAndView detail(@PathVariable("questionId") long questionId, HttpServletRequest request, HttpServletResponse response) throws Exception{ 

不過,我得到一個錯誤,當我運行上面的,並得到:

找不到@PathVariable [questionId@RequestMapping

有沒有人碰到這個纔來的呢?將RequestMapping註釋與現有的XML配置的URL映射混合可以嗎?

+0

離開 細節部分你說你試圖添加'@ RequestMapping'到'MultiActionController'? – skaffman

+0

我只是想說,把uri的一部分移到頂部而不是細節。我編輯了答案來反映這一點。 –

回答

4

這是DefaultAnnotationHandlerMapping類,如果我讀的評論的權利,如果你加在你QuestionController.java頂部@RequestMapping註釋,它可能會解決你的問題

註釋控制器通常標在類型級別使用{@link Controller}原型 。當{@link RequestMapping}在類型級別應用 (因爲此類處理程序通常實現接口org.springframework.web.servlet.mvc.Controller接口)時,這不是必需的。然而, {@link控制器}需要在方法級檢測{@link RequestMapping}註解 如果{@link RequestMapping}不是存在於類型水平。

編輯

你可以做一些這樣的事,URI的/問題部分移動到頂部,並在方法層面

@RequestMapping("/question") 
public class QuestionController 
{ 
    @RequestMapping("/detail/{questionId}") 
    public ModelAndView detail(@PathVariable("questionId") long questionId, HttpServletRequest request, HttpServletResponse response) throws Exception{ 

} 
+0

完美 - 將@RequestMapping添加到課程中,謝謝! – rhinds

相關問題