有人可以解释控制器类是如何工作的

时间:2013-04-10 12:53:29

标签: spring spring-mvc

我正在研究spring样本。我有一个名为UserController2的控制器类,如下所示

@Controller
public class UserController2 extends MultiActionController {

   private UserDAO userDAO;

   public void setUserDAO(UserDAO userDAO) {
    this.userDAO = userDAO;
   }
    @RequestMapping(params = "add", method = RequestMethod.POST)
   public ModelAndView add(HttpServletRequest request,
        HttpServletResponse response, User user) throws Exception {
       userDAO.saveUser(user);
       return new ModelAndView("redirect:User.htm");
  }

  public ModelAndView list(HttpServletRequest request,
        HttpServletResponse response) throws Exception {
      ModelMap modelMap = new ModelMap();
      modelMap.addAttribute("userList", userDAO.listUser());
      modelMap.addAttribute("User", new User());
      return new ModelAndView("userForm", modelMap);
}
}

我有一个名为userForm.jsp的jsp页面

<form:form method="POST" action="add.htm" commandName="User" modelAttribute="User">
   <table>
    <tr>
        <td><form:label path="name">Name</form:label></td>
        <td><form:input path="name" /></td>
    </tr>

    <tr>
        <td><form:label path="id">id</form:label></td>
        <td><form:input path="id" /></td>
    </tr>


    <tr>
        <td><form:label path="password">Name</form:label></td>
        <td><form:input path="password" /></td>
    </tr>

    <tr>
        <td><form:label path="gender">Name</form:label></td>
        <td><form:input path="gender" /></td>
    </tr>

    <tr>
        <td><form:label path="gender">Name</form:label></td>
        <td><form:input path="gender" /></td>
    </tr>

    <tr>
        <td><form:label path="country">Name</form:label></td>
        <td><form:input path="country" /></td>
    </tr>

    <tr>
        <td colspan="2">
          <input type="submit" value="Submit"/>
        </td>
    </tr>
  </table>  
 </form:form>

以下代码实际返回的内容

  return new ModelAndView("userForm", modelMap);

 return new ModelAndView("redirect:User.htm");

我收到以下错误

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

我搜索过但我无法找到关于模式视图的正确解释。

1 个答案:

答案 0 :(得分:0)

使用modelAttribute时,使用户:
1。您的方法参数user使用@ModelAttribute("user")注释2。声明了类型BindingResult的方法参数 此外,注释参数值区分大小写,并且应与您在userForm.jsp中声明的 modelAttribute 的值完全匹配。