Java, Spring Framework MVC - redirection

后端 未结 3 720
感情败类
感情败类 2021-01-26 21:57

I am using spring framework 3. I have a form for posting comments to the article. When the form is submitted, it is checked if there any errors. In case there is no errors, cont

3条回答
  •  长发绾君心
    2021-01-26 22:13

    bkent314 is right:

    Have a look at this two method that is a way that defently works. I separate domain objects from form gui objects (FolderCreateCommand) but that is my style. And in this case I use ModelAndView for return instead of string, because so I have full controll to the model.

    @RequestMapping(method = RequestMethod.GET, params = "form")
    public ModelAndView createForm() {
        return modelAndViewForCreate(new FolderCreateCommand(..default values..));
    }
    
    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView create(@Valid FolderCreateCommand folderCreateCommand,
              BindingResult bindingResult) {
    
        if (bindingResult.hasErrors()) {
            return modelAndViewForCreate(folderCreateCommand);
        }
        Folder folder = this.folderService.createFolder(folderCreateCommand);
        return redirectToShow(folder);
    }
    
    
    private ModelAndView modelAndViewForCreate(FolderCreateCommand folderCreateCommand) {
        ModelMap uiModel = new ModelMap();
        uiModel.addAttribute("folderCreateCommand", folderCreateCommand);
        uiModel.addAttribute("parentFolders", this.folderDao.readAll());
        return new ModelAndView("folders/create", uiModel);
    }
    
    private ModelAndView redirectToShow(Folder folder) {
        return new ModelAndView(new RedirectView("/folders/" + folder.getId(), true));
    }
    

提交回复
热议问题