在SpringBoot中处理表单提交

时间:2018-01-13 16:43:14

标签: spring validation spring-boot

这是我的控制器:

@Controller
@RequestMapping("/accounts/*")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @GetMapping
    public ModelAndView home() {
        final ModelAndView modelAndView = new ModelAndView();
        final List<Account> accountsForCurrentUser = this.accountService.getAccountsForCurrentUser();
        modelAndView.addObject("accounts", accountsForCurrentUser);
        modelAndView.setViewName("pages/accounts/index");
        return modelAndView;
    }

    @GetMapping("create")
    public ModelAndView create() {
        final ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("account", new Account());
        modelAndView.setViewName("pages/accounts/create");
        return modelAndView;
    }

    @PostMapping("create")
    public ModelAndView createSubmit(@Valid @ModelAttribute(name = "account") Account account, BindingResult bindingResult, ModelAndView modelAndView) {
        if (bindingResult.hasErrors()) {
            return modelAndView;
        }

        return new ModelAndView("redirect:/accounts");
    }
}

我想做的是在验证表单时将用户重定向到/ accounts /,但如果报告错误,则会将他带回/ accounts / create /并显示错误。

但是,出错,我有:

  

解析模板&#34; accounts / create&#34;时出错,模板可能不存在,或者任何配置的模板解析器都无法访问

1 个答案:

答案 0 :(得分:2)

您还需要在post / create方法中设置模型和视图名称。

顺便说一下,使用ModelAndView的处理方法是有效的,但我认为最好使用String方法。阅读和标准方式要好得多。所以你的控制器看起来像:

@Controller
@RequestMapping("/accounts")
public class AccountController {

    @Autowired
    private AccountService accountService;

    @GetMapping("")
    public String home(Model Model) {
        List<Account> accountsForCurrentUser = this.accountService.getAccountsForCurrentUser();
        model.addAttribute("accounts", accountsForCurrentUser);
        return "pages/accounts/index";
    }

    @GetMapping("/new")
    public String newAccount(Model model) {
        model.addAttribute("account", new Account());
        return "pages/accounts/create";
    }

    @PostMapping("/new")
    public String createAccount(@Valid @ModelAttribute Account account, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return "pages/accounts/create";
        }
        "redirect:/accounts";
    }
}