Spring 3 MVC错误:BindingResult和bean名称'user'的普通目标对象都不可用

时间:2011-10-19 14:46:39

标签: spring-mvc

我知道这个问题可能已在其他地方得到解决,但我无法找到解决问题的满意方案。顺便说一下,我正在使用spring 3.0.2

的Login.jsp

<form:form id="_LoginForm" name="LoginForm" modelAttribute="user" action="login" method="POST">
    <form:input path="username" value=""/>
    <form:input path="password" value=""/>
    <input type="submit" value="Submit"/>

LoginController.java

@RequestMapping(value="login", method=RequestMethod.POST)
public String login(@ModelAttribute("user") User user, BindingResult result) {
    System.out.println("recd request");
    return null;
}

当我尝试访问login.jsp页面时,出现以下错误:

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'user' available as request attribute
    at org.springframework.web.servlet.support.BindStatus.(BindStatus.java:141)
    at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:174)
    at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:194)
    at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:160)
    at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:123)
    at org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:409)
    at org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:140)
    at org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:102)

2 个答案:

答案 0 :(得分:1)

您能否在控制器中提供 RequestMethod.GET 方法? 只是想确保在 GET 方法中添加modelAttribute。

答案 1 :(得分:0)

我添加了以下方法来完成这项工作,但我觉得必须有一种更好的方法来实现这一点,而无需每次都编写设置方法。

的applicationContext.xml

<mvc:view-controller path="/" view-name="index" />

的index.jsp

<jsp:forward page="index.action"/>

LoginController.java

@RequestMapping(value="index.action", method=RequestMethod.GET)
public String setupLogin(Map<String, Object> modelMap) {        
    modelMap.put("user", new User());
    return "Login";
}