Search code examples
validationspring-mvcannotationshibernate-validator

How to reject a field from bean for validation when binding?


I have three fields department_Id,department_Name,department_location in departmentForm act as a model object in this model form.

I have use annotation to validate the fields. Now, I want to only use two fields in different jsp page say create.jsp and one field in different jsp page say getDepartmentById.

When I press submit button of create.jsp, validation is happening but after providing correct information its not submitted cause in this page.

I haven't give one field department_Id which is auto generated by my DAO layer. So, please help me, how to reject this value to execute my create.jsp page for successfully creating department in database.

When I printed the BindingResult object, it shown as follow:

Field error in object 'departmentForm' on field 'departmentId': rejected value [null]; 
codes [NotEmpty.departmentForm.departmentId,NotEmpty.departmentId,NotEmpty.java.lang.String,NotEmpty]; 
arguments [org.springframework.context.support.DefaultMessageSourceResolvable: 
codes [departmentForm.departmentId,departmentId]; arguments []; 
default message [departmentId],org.hibernate.validator.constraints.NotEmpty.message},
[Ljava.lang.Class;@4fc4a198,[Ljava.lang.Class;@764d2b11]; 
default message [may not be empty]`

This is how I coded in controller:

@RequestMapping(value = "/createDepartment", method = RequestMethod.POST)
public String createEmployee(@Valid DepartmentForm departmentForm,
        BindingResult bindingResult, Map<String, DepartmentForm> model)
        throws Exception {

    if (bindingResult.hasErrors()) {
        System.out.println(bindingResult);
        bindingResult.reject(departmentForm.getDepartmentId());
        return "departmentForm";
    }
    System.out.println("mr ankur jadiy");

    model.put("departmentForm", departmentForm);
    departmentForm.setUpdateStatus('A');
    if (departmentForm.getUpdateStatus() == 'A') {
        departmentServiceImpl
            .actionDecider(convertDeptFormToDeptBO(departmentForm));

    }
    return "Success";
}

my DepartmentForm code is as follow:

package com.nousinfo.tutorial.model;

import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.NotEmpty;

public class DepartmentForm {

    @NotEmpty
    @Size(min = 1, max = 20,message="")
    private String departmentId;
    @NotEmpty
    private String departmentName;

    private String departmentLocation;

    private Character updateStatus;
    public String getDepartmentId() {
        return departmentId;
    }

    public void setDepartmentId(String departmentId) {
        this.departmentId = departmentId;
    }

    public String getDepartmentName() {
        return departmentName;
    }

    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }

    public String getDepartmentLocation() {
        return departmentLocation;
    }

    public void setDepartmentLocation(String departmentLocation) {
        this.departmentLocation = departmentLocation;
    }

    public Character getUpdateStatus() {
        return updateStatus;
    }

    public void setUpdateStatus(Character updateStatus) {
        this.updateStatus = updateStatus;
    }
}

and my create.jsp is

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://jakarta.apache.org/taglibs/input-1.0" prefix="input"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="s"%>
<%@ 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>Create Department</title>
<link rel="stylesheet" href="css/style.css" type="text/css"></link>
</head>

<body>

    <table width="1254" height="74" border="0" align="center">

        <tr>
            <td width="300" height="68" align="center" bgcolor="#99CCFF"><h2>
                    <span class="style1">Employee Details </span>
                </h2></td>
            <td width="100" height="68" align="center" bgcolor="#FFFFFF"><img
                src="./image/emps.jpg" width="190" height="92" /></td>
        </tr>
    </table>
    <p>
        <br />
    </p>
    <hr size="1" width="786">
    <form:form id="form" method="post" action="/EmployeeWebSpring/departmentController/createDepartment"
        modelAttribute="departmentForm">
        <table>
            <tr>
                <form:hidden path="updateStatus" />
            </tr>

            <tr>
                <td>
                    Department_Name:
                    <font color="red"><form:errors path="departmentName" /></font>
                </td>
            </tr>
            <tr>
                <td><form:input path="departmentName" /></td>
            </tr>

            <tr>
                <td>
                    Department_Location:
                    <font color="red"><form:errors path="departmentLocation" /></font>
                </td>
            </tr>
            <tr>
                <td><form:input path="departmentLocation" /></td>
            </tr>
        </table>

        <br>
        <br />
        <p>&nbsp;</p>
        <br>
        <tr>
            <td><input type="submit" name="method" value="save" /></td>
            <td><input type="submit" name="method" value="cancel" /></td>
        </tr>

        <hr size="1" width="786">
        <p>&nbsp;</p>
    </form:form>
</body>
</html>

Solution

  • What the error says is that you're missing value for departmentId, which is not surprising since you defined it as

    @NotEmpty
    @Size(min = 1, max = 20,message="")
    

    You don't really need to validate departmentId if it's autogenerated by your code. You probably should remove it from the DepartmentForm, especially since it's not in the form, or at least make it optional.

    You can make it mandatory in your business object, but the form backing object should reflect what's in the form.

    update

    If departmentId is a database-generated id, you should set it as disallowed in your controller's InitBinder:

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.setDisallowedFields(new String[] { "departmentId" }); 
    }