1

Trying to get Spring annotation based validation working in a simple webapp. While using @ModelAttribute along with @Valid, I am getting validation error next to the field, however when I am adding object to model, not getting error messages.

Suggest any alternative approach to display form validation error message(i.e. without using @ModelAtrribute along with @Valid)

Below is the code:

EmployeeModel.java

@Entity
@Table(name = "Employee")
public class EmployeeModel implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "ID")
    @NotNull(message = "ID is required")
    private Integer employee_id;

    @Column(name = "Name")
    @NotEmpty(message = "Name is required")
    private String employee_name;

    @Column(name = "Manager")
    private String manager;

    public Integer getEmployee_id() {
        return employee_id;
    }

    public void setEmployee_id(Integer employee_id) {
        this.employee_id = employee_id;
    }

    public String getEmployee_name() {
        return employee_name;
    }

    public void setEmployee_name(String employee_name) {
        this.employee_name = employee_name;
    }

    public String getManager() {
        return manager;
    }

    public void setManager(String manager) {
        this.manager = manager;
    }

    @Override
    public String toString() {
        return "Employee [id=" + employee_id + ", Name=" + employee_name
                + ", Manager=" + manager + "]";
    }
}

Code snippet in Controller

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveEmployee(Model model, @Valid EmployeeModel employee, BindingResult result) {
    if (result.hasErrors()) {
        model.addAttribute("employee", employee);
        //model.addAttribute(employee);
        return "EmployeeForm";
    }
    employeeService.addEmployee(employee);
    return "forward:/";
}

View:

<form:form action="save" method="post" modelAttribute="employee">
                <tr>
                    <td><form:label path="employee_id">Employee ID:</form:label></td>
                    <td><form:input path="employee_id" /></td>
                    <td><form:errors path="employee_id"/></td>
                </tr>
                <tr>
                    <td><form:label path="employee_name">Employee Name:</form:label></td>
                    <td><form:input path="employee_name" /></td>
                    <td><form:errors path="employee_name"/></td>
                </tr>
                <tr>
                    <td><form:label path="manager">Manager:</form:label></td>
                    <td><form:input path="manager" /></td>
                </tr>
                <tr>
                    <td colspan="2" align="center"><input type="submit"
                        value="Save"></td>
                </tr>
            </form:form>

In case I use the commented line

//model.addAttribute(employee)

I get exception stating: java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'employee' available as request attribute.

Replacing the commented line with

model.addAttribute("employee",employee)

Page gets loaded with the previous value entered which means invalid object is not getting replaced, still error message is not displayed.

The above can be achieved using @ModelAttribute along with @Valid, but is there any other alternative i.e. without using @ModelAtrribute?

What is the difference in working with @ModelAttribute and Model, as till now I considered both works in similar way?

5
  • The Model and BindingResult are both the model. However when using Model you loose all the additional information available in BindingResult. Simply put don't use both, and what you do is something you shouldn't be doing. You aren't actually using a model but a just constructed object. Next to @Valid add @ModelAttribute("employee") to your method and remove the Model argument. Relaunch...
    – M. Deinum
    Oct 7, 2016 at 11:53
  • Is there any alternative approach to display validation error message (without using @ModelAttribute) Oct 7, 2016 at 13:41
  • 1
    Don't use the Model and use result.getModel().add("employee", employee) might work. BUt why make it more complex, let Spring handle it for you.
    – M. Deinum
    Oct 10, 2016 at 6:11
  • I encounter the same issue before. Assuming if I don't want to use Valid and ModelAttribute("employee") annotations together, is it possible just to use @Valid, and programmatically pass the model into the modelmap, such that the form is able display the error message. In case anyone ask me, why would i want to do that, my response would be, just wanted to know if possible, for the sake of learning purpose.
    – Nick Wills
    May 27, 2021 at 12:36
  • If u can't use @ModelAttribute("employee") for some reason, u can try this. It just works for me... In the parameter, include ModelMap mm. Then do this, mm.put(BindingResult.class.getName() + ".employee", result);
    – Nick Wills
    May 27, 2021 at 13:01

1 Answer 1

0

@ModelAttribute populates the fields of a class, which then populates an attribute of the model to be passed back to the view.

Also you make following change on your saveEmployee method. You do not need to add attribute to model. @ModelAttribute automatically add for you.

@RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveEmployee(@Valid @ModelAttribute(name = "employee") EmployeeModel employee, BindingResult result) {
    if (result.hasErrors()) {
        return "EmployeeForm";
    }
    employeeService.addEmployee(employee);
    return "forward:/";
}
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.