既不是BindingResult也不是普通的目标对象……例外

是的,我读到这是很常见的问题,但阅读这些post并没有真正帮助我。

简短的故事是我想在showAllComments.jsp上提交一份表格

COMMENT

这是控制器:

 @Controller @SessionAttributes public class CommentController { @Autowired private CommentService commentService; @RequestMapping(value = "/postNewComment", method = RequestMethod.POST) public ModelAndView showAllUsers(@ModelAttribute("command") Comment comment, BindingResult result) { System.out.println(comment.getComment()); Map model = new HashMap(); model.put("COMMENTS", commentService.getComments()); return new ModelAndView("showAllComments", model); } } 

结果如下: java.lang.IllegalStateException:BindingResult和bean名称’command’的普通目标对象都不能作为请求属性使用

但是,您可能需要从头开始查看整个故事 :用户通过单击启动index.jsp上的应用程序

 Log in 

该链接将他带到LoginController

 @RequestMapping("/toLoginPage") public ModelAndView goToLoginPage() { return new ModelAndView("login", "command", new User()); } 

然后他被带到login.jsp,在那里他提供了他的用户名和密码。

 

他提交表单,然后将其带回LoginController

 @RequestMapping(value = "/log_in", method = RequestMethod.POST) public ModelAndView tryToLogin(@RequestParam("uName") String uName, @RequestParam("pW") String pW, HttpServletResponse response, HttpServletRequest request) { ModelAndView ret = new ModelAndView("login", "command", new User()); User user = userService.existingUser(uName, pW); loggedInUser = new User(); if (user != null) { Map model = new HashMap(); model.put("COMMENTS", allComments); model.put("LOGGED_IN_USER", loggedInUser); ret = ModelAndView("showAllComments", model); } return ret; } 

成功登录后,他在showAllComments页面上看到所有评论,他应该能够添加自己的评论,但提交上述表格会抛出上述exception。 我觉得缺少了一些东西,但我无法弄清楚它是什么。 只是为了记录我显示web.xml

   Spring3MVC  spring org.springframework.web.servlet.DispatcherServlet 1   spring *.html   index.jsp   

和spring-servlet.xml

                     net.model.User net.model.Comment     ${hibernate.dialect} ${hibernate.show_sql}                       

当您在logincontroller中显示showAllComments.jsp时,需要添加一个表单bean类,即Comment,作为模型的属性。

 @RequestMapping(value = "/log_in", method = RequestMethod.POST) public ModelAndView tryToLogin(@RequestParam("uName") String uName, @RequestParam("pW") String pW, HttpServletResponse response, HttpServletRequest request) { ModelAndView ret = new ModelAndView("login", "command", new User()); User user = userService.existingUser(uName, pW); loggedInUser = new User(); model.addAttribute("command", new Comment()); if (user != null) { Map model = new HashMap(); model.put("COMMENTS", allComments); model.put("LOGGED_IN_USER", loggedInUser); ret = ModelAndView("showAllComments", model); } return ret; } 

这应该工作正常。

UPDATE

使用’command’作为命令对象名称不是一个好习惯。 对于课堂评论,您可以使用“评论”或类似的东西。 如果您这样做,请使用以下代码更新您的表单。

  
COMMENT

在所有其他地方做同样的改变,即

 model.addAttribute("comment", new Comment()); 

 @ModelAttribute("comment") 

更新2

  @RequestMapping(value="userRegistration", method = RequestMethod.GET) public ModelAndView showUserRegistrationForm(Model model){ model.addAttribute("user", new AccountDetailsForm()); return new ModelAndView("userRegistration"); }