2011-01-07 14 views

回答

61

@Controller是一種更靈活的方式來定義窗體/嚮導。您應該根據請求的路徑/請求參數/請求方法將方法映射到請求。因此,您可以根據需要定義您的嚮導步驟(也可以更透明地處理命令對象),而不是定義視圖列表並處理基於某些必需的「步驟」參數的請求。以下是您如何模擬經典的AWFC功能(這僅僅是一個示例,您可以做更多的事情)。

@Controller 
@RequestMapping("/wizard.form") 
@SessionAttributes("command") 
public class WizardController { 

    /** 
    * The default handler (page=0) 
    */ 
    @RequestMapping 
    public String getInitialPage(final ModelMap modelMap) { 
     // put your initial command 
     modelMap.addAttribute("command", new YourCommandClass()); 
     // populate the model Map as needed 
     return "initialView"; 
    } 

    /** 
    * First step handler (if you want to map each step individually to a method). You should probably either use this 
    * approach or the one below (mapping all pages to the same method and getting the page number as parameter). 
    */ 
    @RequestMapping(params = "_step=1") 
    public String processFirstStep(final @ModelAttribute("command") YourCommandClass command, 
            final Errors errors) { 
     // do something with command, errors, request, response, 
     // model map or whatever you include among the method 
     // parameters. See the documentation for @RequestMapping 
     // to get the full picture. 
     return "firstStepView"; 
    } 

    /** 
    * Maybe you want to be provided with the _page parameter (in order to map the same method for all), as you have in 
    * AbstractWizardFormController. 
    */ 
    @RequestMapping(method = RequestMethod.POST) 
    public String processPage(@RequestParam("_page") final int currentPage, 
           final @ModelAttribute("command") YourCommandClass command, 
           final HttpServletResponse response) { 
     // do something based on page number 
     return pageViews[currentPage]; 
    } 

    /** 
    * The successful finish step ('_finish' request param must be present) 
    */ 
    @RequestMapping(params = "_finish") 
    public String processFinish(final @ModelAttribute("command") YourCommandClass command, 
           final Errors errors, 
           final ModelMap modelMap, 
           final SessionStatus status) { 
     // some stuff 
     status.setComplete(); 
     return "successView"; 
    } 

    @RequestMapping(params = "_cancel") 
    public String processCancel(final HttpServletRequest request, 
           final HttpServletResponse response, 
           final SessionStatus status) { 
     status.setComplete(); 
     return "canceledView"; 
    } 

} 

我試着改變方法簽名,以便您可以瞭解我提到的靈活性。當然,還有很多更給它:你可以在@RequestMapping使用請求方法(GET或POST),你可以定義@InitBinder註釋的方法等

編輯:我有一個映射的方法我解決了這個問題(順便說一下,您需要確保您沒有模糊的映射 - 可以映射到多個方法的請求 - 或未映射的請求 - 不能映射到任何方法的請求)。還可以看看@SessionAttributes,@SessionStatus和@ModelAttribute,它們也是完全模擬經典AWFC行爲所需要的(我已經編輯了代碼,以使其清晰)。

+5

+1這肯定比Spring文檔/示例應用程序提供的更好的解釋。很多人都覺得這很有幫助。 – prasopes 2011-01-07 11:08:55