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

“BindingResult 和 Bean 名称'命令'的纯目标对象都不能用作请求属性”

李文轩
2023-03-14

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

“BindingResult 和 Bean 名称'命令'的纯目标对象都不能用作请求属性”

jsp 页面是索引.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个答案

伏建修
2023-03-14

我发现问题出在method type = "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";
    }
}
 类似资料: