当我运行以下代码并按url调用addEmployee()方法时。代码在验证时间中断:
我收到以下错误:

  java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute


项目结构为:
java - Spring validator 抛出异常-LMLPHP
型号类别:

  public class Employee {
    private int empId;
    private String name;
    private String password;
    private String gender;
    private Long salary;
    private int age;
    private List<String> courses;
    private String tutor;
    getters and setters()
}


控制器类:

@Controller

public class EmployeeController {

    @Autowired
    @Qualifier("formValidator")
    private Validator validator;

    @InitBinder
    private void initBinder(WebDataBinder binder) {
        binder.setValidator(validator);
    }

    @RequestMapping(value = "/employee", method = RequestMethod.GET)
    public ModelAndView employee() {
        List<String> courses = new ArrayList<String>();
        courses.add("Maths");
        courses.add("Physics");
        courses.add("Geometry");
        courses.add("Algebra");
        courses.add("Painting");

        List<String> genders = new ArrayList<String>();
        genders.add("Male");
        genders.add("Female");

        List<String> tutors = new ArrayList<String>();
        tutors.add("Mrs Smith");
        tutors.add("Mr Johnson");
        tutors.add("Mr Clarks");

        // default bean name is command
        ModelAndView modelAndView = new ModelAndView("employeeForm", "command", new Employee());
        modelAndView.addObject("tutors", tutors);
        modelAndView.addObject("genders", genders);
        modelAndView.addObject("courses", courses);

        return modelAndView;
    }

    @RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
    public String addEmployee(@Valid @ModelAttribute Employee employee, BindingResult result, ModelMap model) {
        if (result.hasErrors()) {
            return "employeeForm";
        }
        model.addAttribute("empId", employee.getEmpId());
        model.addAttribute("name", employee.getName());
        model.addAttribute("password", employee.getPassword());
        model.addAttribute("gender", employee.getGender());
        model.addAttribute("salary", employee.getSalary());
        model.addAttribute("age", employee.getAge());
        model.addAttribute("courses", employee.getCourses());
        model.addAttribute("tutor", employee.getTutor());
        return "employeeDetail";
    }

}


验证者类别:

    public class FormValidator implements Validator {


    public boolean supports(Class<?> paramClass) {
        return Employee.class.equals(paramClass);
    }

    public void validate(Object obj, Errors errors) {
        try {
            Employee emp = (Employee) obj;
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "empId", "valid.empId");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "valid.name");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "valid.password");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "gender", "valid.gender");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "salary", "valid.salary");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "age", "valid.age");
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "tutor", "valid.tutor");
            List<String> courses = emp.getCourses();
            if (courses == null || courses.size() < 2) {
                errors.rejectValue("courses", "valid.courses");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


{Name} -servlet.xml

<!-- Enable annotation driven controllers, validation etc... -->
<mvc:annotation-driven></mvc:annotation-driven>

<context:component-scan base-package="com.bits.emp.controller"></context:component-scan>
<bean id="messageSource"
    class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="validation" />
</bean>

<bean id="formValidator" class="com.bits.emp.validator.FormValidator" />


<bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/"></property>
    <property name="suffix" value=".jsp"></property>
</bean>


employeeForm.jsp

    <form:form method="POST" action="/sdnext/addEmployee">
    <table>
        <tr>
            <td width="127"><form:label path="empId">Employee Id:</form:label></td>
            <td width="102"><form:input path="empId" /></td>
            <td><form:errors path="empId" cssStyle="color: #ff0000;" /></td>

        </tr>
        <tr>
            <td><form:label path="name">Employee Name:</form:label></td>
            <td><form:input path="name" /></td>
            <td><form:errors path="name" cssStyle="color: #ff0000;" /></td>

        </tr>
        <tr>
            <td><form:label path="password">Password :</form:label></td>
            <td><form:password path="password" showPassword="true" /></td>
            <td><form:errors path="password" cssStyle="color: #ff0000;" /></td>

        </tr>
        <tr>
            <td><form:label path="gender">Gender :</form:label></td>
            <td><form:radiobuttons path="gender" items="${genders}" /></td>
            <td><form:errors path="gender" cssStyle="color: #ff0000;" /></td>

        </tr>
        <tr>
            <td><form:label path="salary">Employee Salary:</form:label></td>
            <td><form:input path="salary" /></td>
            <td><form:errors path="salary" cssStyle="color: #ff0000;" /></td>

        </tr>
        <tr>
            <td><form:label path="age">Employee Age:</form:label></td>
            <td><form:input path="age" /></td>
            <td><form:errors path="age" cssStyle="color: #ff0000;" /></td>

        </tr>
        <tr>
            <td><form:label path="courses">Courses:</form:label></td>
            <td><form:checkboxes path="courses" items="${courses}" /></td>
            <td><form:errors path="courses" cssStyle="color: #ff0000;" /></td>

        </tr>
        <tr>
            <td>Please select your tutor:</td>
            <td><form:select path="tutor">
                    <form:option value="" label="...." />
                    <form:options items="${tutors}" />
                </form:select></td>
            <td><form:errors path="tutor" cssStyle="color: #ff0000;" /></td>
        </tr>

        <tr>
            <td colspan="2"><input type="submit" value="Submit" /></td>
        </tr>
    </table>
</form:form>


请提出为什么我会收到此错误以及如何解决此问题。提前致谢。

最佳答案

控制器类中的addEmployee方法参数错误。您应该定义表单中使用的模型属性。尝试将方法更改为此:

@RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
public String addEmployee(@ModelAttribute("command") @Valid Employee employee, BindingResult result, ModelMap model) {

07-26 09:24