" BindingResult和bean名称'命令'都没有普通的目标对象。可用作请求属性"

时间:2016-09-05 17:52:53

标签: spring jsp spring-mvc servlets

使用spring forms标记库

创建表单时出现异常

"无论是BindingResult还是bean名称的明确目标对象'命令'可用作请求属性"

jsp页面是index.jsp

<%@ include file="views/static_include.jsp" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login to AVA Corp</title>
</head>
<body>
<form:form method="POST" commandName="user" action="login.jsp">  
<table>  
    <tbody><tr>  
        <td><form:label path="firstName">Name:</form:label></td>  
        <td><form:input path="firstName"></form:input></td>  
    </tr>  
    <tr>  
        <td><form:label path="age">Age:</form:label></td>  
        <td><form:input path="age"></form:input></td>  
    </tr>  
    <tr>  
        <td colspan="2">  
            <input type="submit" value="Submit">  
        </td>  
        <td></td>  
        <td></td>  
    </tr>  
</tbody></table>    
</form:form> 
</body>
</html>

bean类是:

import java.io.Serializable;

public class Person implements Serializable {

    private static final long serialVersionUID = 1949001721422434327L;

    private String firstName;
    private Integer age;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

}

控制器类是

@Controller
public class LoginController {

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView initForm(Model model) {
        return new ModelAndView("index", "user", new Employee());
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(@ModelAttribute("user") Employee employee, BindingResult result, SessionStatus status){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user", employee); 
        return "UserFormSuccess";
    }
}

1 个答案:

答案 0 :(得分:0)

我发现问题出在控制器方法中,方法类型=“get”。请求方法的值必须是表单所在页面的URL映射,例如在我们的例子中index.jsp所以控制器类将是

@Controller
public class LoginController {

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView initForm(Model model) {
        return new ModelAndView("index", "user", new Employee());
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(@ModelAttribute("user") Employee employee, BindingResult result, SessionStatus status){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("user", employee); 
        return "UserFormSuccess";
    }
}