2012-05-29 61 views
1

嘗試訪問控制器時出現問題。BindingResult和bean名稱'index'的普通目標對象都不能作爲請求屬性

這裏是我的控制器:

@Controller 
@RequestMapping("/index.htm") 
public class LoginController { 

    @Autowired 
    private UserService userService; 

    @RequestMapping(method = RequestMethod.GET) 
    public String showForm(Map model) { 
     model.put("index", new LoginForm()); 
     return "index"; 
    } 

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

     if (result.hasErrors()) { 
      HashMap<String, String> errors = new HashMap<String, String>(); 
      for (FieldError error : result.getFieldErrors()) { 
       errors.put(error.getField(), error.getDefaultMessage()); 
      } 
      model.put("errors", errors); 
      return "index"; 
     } 

     List<User> users = userService.getUsers(); 
     loginForm = (LoginForm) model.get("loginForm"); 

     for (User user : users) { 
      if (!loginForm.getEmail().equals(user.getEmail()) || !loginForm.getPassword().equals(user.getPassword())) { 
       return "index"; 
      } 
     } 

     model.put("index", loginForm); 
     return "loginsuccess"; 
    } 

} 

這裏是我的形式:

<form:form action="index.htm" commandName="index"> 

     <table border="0" cellspacing="12"> 
      <tr> 
       <td> 
        <spring:message code="application.loginForm.email"/> 
       </td> 
       <td> 
        <form:input path="email"/> 
       </td> 
       <td class="error"> 
        <form:errors path="email"/> 
       </td> 
      </tr> 
      <tr> 
       <td> 
        <spring:message code="application.loginForm.password"/> 
       </td> 
       <td> 
        <form:password path="password"/> 
       </td> 
       <td class="error"> 
        <form:errors path="password"/> 
       </td> 
      </tr> 
      <tr> 
       <td> 
        <input type="submit" value="Submit"/> 
       </td> 
      </tr> 
     </table> 

    </form:form> 

在表單提交我得到這個異常:

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

我在做什麼錯在這裏?

回答

2

這是因爲你只是在做此位下底部

model.put("index", loginForm); 

如果從驗證錯誤返回,或從一個成功的,有名爲「指數」模型地圖不支持對象所以你的表格標籤有commandName="index"

常見的解決方案是簡單地做到這一點

@ModelAttribute("index") 
public LoginForm getLoginForm() { 
    return new LoginForm(); 
} 

然後總會有一個存在,並且你可以將它添加了GET方法。

+0

謝謝,這解決了我的問題。 –

相關問題