2012-09-25 57 views
1

我無法理解我在做什麼錯誤。我有一個控制器:保持得到: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<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<Account> accounts = accountService.findAll(); 
     loginForm = (LoginForm) model.get("loginForm"); 


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

} 

春季HTML表單:

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

    <table cellspacing="10"> 
     <tr> 
      <td> 
       <form:label path="username"> 
        <spring:message code="main.login.username"/> 
       </form:label> 
      </td> 
      <td> 
       <form:input path="username" cssClass="textField"/> 
      </td> 
     </tr> 
     <tr> 
      <td> 
       <form:label path="password"> 
        <spring:message code="main.login.password"/> 
       </form:label> 
      </td> 
      <td> 
       <form:password path="password" cssClass="textField"/> 
      </td> 
     </tr> 
     <tr> 
      <td> 
       <input type="submit" class="button" value="Login"/> 
      </td> 
     </tr> 
    </table> 

</form:form> 

當我試圖訪問網址:http://localhost:8080/webclient/index.htm

我不斷收到此異常:

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

什麼我的控制器有問題,爲什麼我一直得到這樣的異常?

+0

也許嘗試刪除'commandName =「index」'? – vacuum

+0

已經嘗試過,如果我刪除它,我得到:既沒有BindingResult也沒有bean名稱的命令對象作爲請求屬性可用。有「命令」而不是「索引」。 –

+0

不應該是'modelAttribute'而不是'commandName'? – Pao

回答

0

我會做出以下更改。首先你GET方法應該是這樣的:

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

使用@ModelAttribute註釋會自動把「指數」到模型的請求。

而且你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」請求。

+0

謝謝,我會盡力讓你知道。 –

相關問題