继续获取:BindingResult和bean名称’index’的普通目标对象都不可用作请求属性

我无法理解我做错了什么。 我有一个控制器:

@Controller @RequestMapping(value = "/index.htm") public class LoginController { @Autowired private AccountService accountService; @RequestMapping(method = RequestMethod.GET) public String showForm(Map model) { model.put("index", new LoginForm()); return "index"; } @ModelAttribute("index") public LoginForm getLoginForm() { return new LoginForm(); } @RequestMapping(method = RequestMethod.POST) public String processForm(LoginForm loginForm, BindingResult result, Map model) { if (result.hasErrors()) { HashMap errors = new HashMap(); for (FieldError error : result.getFieldErrors()) { errors.put(error.getField(), error.getDefaultMessage()); } model.put("errors", errors); return "index"; } List accounts = accountService.findAll(); loginForm = (LoginForm) model.get("loginForm"); model.put("index", loginForm); return "loginsuccess"; } } 

和Spring html表单:

 

当我尝试访问URL时: http://localhost:8080/webclient/index.htm

我一直得到这个例外:

 java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'index' available as request attribute 

我的控制器出了什么问题,为什么我一直得到这样的例外?

我会做出以下更改。 首先你的GET方法应该是这样的:

 @RequestMapping(method = RequestMethod.GET) public String showForm(@ModelAttribute("index") LoginForm loginForm) { return "index"; } 

使用@ModelAttribute注释会自动将“index”放入请求的模型中。

你的POST方法声明应该是这样的:

 @RequestMapping(method = RequestMethod.POST) public String processForm(@ModelAttribute("index") LoginForm loginForm, BindingResult result, Map model) { 

最后,也许是真正的问题,将控制器类的@RequestMapping注释更改为:

 @RequestMapping(value = "/index") 

你拥有的“.htm”是多余的。 您已经配置了web.xml和Spring配置来响应“.htm”请求。