Spring验证器抛出异常

时间:2016-05-04 13:33:13

标签: java spring validation jsp spring-mvc

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

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

项目结构是: enter image description here 型号类:

  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();
        }
    }
}

{名称} -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>

请说明我收到此错误的原因以及解决方法。提前谢谢。

1 个答案:

答案 0 :(得分:1)

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

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