"Neither BindingResult nor plain target object for bean name 'command' available as request attri



在使用spring forms标签库创建表单时出现异常

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

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";
    }
}

我发现问题是与方法类型=" 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";
    }
}

相关内容

最新更新