1

コントローラにアクセスしようとすると問題が発生します。

これが私のコントローラーです:

@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.

私はここで何が間違っているのですか?

4

1 に答える 1

2

それはあなたが一番下でこのビットをやっているだけだからです

model.put("index", loginForm);

検証エラーまたは成功から戻った場合、モデルマップに「index」という名前のバッキングオブジェクトがないため、commandName="index"ピッチのあるフォームタグが適合します。

一般的な解決策は、これを単純に行うことです

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

そうすれば、常に1つ存在し、GETメソッドから追加することができます。

于 2012-05-29T16:53:41.830 に答える