当前位置: 首页 > 知识库问答 >
问题:

“bean名称'command'的BindingResult和普通目标对象都不能作为请求属性使用”

石俊雄
2023-03-14

我在使用spring forms标记库创建表单时遇到一个异常

“bean名称'command'的BindingResult和普通目标对象都不能作为请求属性使用”

<%@ 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类是

@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个答案

岳正浩
2023-03-14

我发现问题出在方法类型=“get”的controller方法上。request方法的值需要是表单所在页面的URL映射,在我们的例子中是index.jsp,因此controller类将

@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";
    }
}
 类似资料: