org.springframework.validation.BeanPropertyBinding

2019-08-07 06:36发布

问题:

Controller class-

@Controller
@SessionAttributes({"id", "roleId"})
@RequestMapping("/User")
public class UserController {

@Autowired
private UserService userv = null;           

@InitBinder("stdUser")
private void initBinder(WebDataBinder binder) {
    System.out.println("1111======"+binder.getObjectName());
    binder.setValidator(new NewUserValidator());
    System.out.println("2222======"+binder.getObjectName());
}

@RequestMapping(value = "/allUsers")
public ModelAndView allUser(@ModelAttribute("userSetup")@Valid UserBean stdUser, BindingResult result, Map<String, Object> map, HttpSession session) {
    StdCheckAccessV chk = new StdCheckAccessV();
    chk.setFexe(Screens.User.substring(Screens.User.lastIndexOf("/") + 1, Screens.User.length()));
    chk.setUid(Long.parseLong(session.getAttribute("id").toString().trim()));
    chk.setRid(Long.parseLong(session.getAttribute("roleId").toString().trim()));
    chk = userv.getAccess(chk);
    List<StdUsers> l = userv.getUsersList();
    stdUser.setChkAccessV(chk);
    map.put("userList", l);
    return new ModelAndView(Screens.User);
}
@RequestMapping(value = "/submitUser")
public ModelAndView addOrUpdate(@ModelAttribute("userSetup")@Valid UserBean stdUser, BindingResult result, HttpSession session, final RedirectAttributes redA) {
    try {
        int res = 0;
        Long id = stdUser.getStdUsers().getId();
        if (result.hasErrors()) {
            System.out.println("///////result has errors   " + result.toString());
            return new ModelAndView("redirect:/User/allUsers");
        }
        System.out.println("////////the id============"+id);
        if (id == null) {
            System.out.println("/////inside the if");
            stdUser.getStdUsers().setUserGroupId(Long.parseLong(session.getAttribute("id").toString().trim()));
            stdUser.getStdUsers().setCreatedBy(Long.parseLong(session.getAttribute("id").toString().trim()));
            stdUser.getStdUsers().setCreationDate(new Date());
            res = userv.submitUser(stdUser);
        } else {
            System.out.println("/////inside the else");
            stdUser.getStdUsers().setUpdateDate(new Date());
            stdUser.getStdUsers().setUpdatedBy(Long.parseLong(session.getAttribute("id").toString().trim()));
            res = userv.updateUser(stdUser);
        }
    } catch (Exception e) {
        System.out.println("////Exception in add or update method " + e);
    }
    return new ModelAndView("redirect:/User/allUsers");
    //return "redirect:/User/allUsers";
}}

Validator class-

@Component
public class NewUserValidator implements Validator {

@Override
public boolean supports(Class<?> userOb) {
    return UserBean.class.equals(userOb);
}

@Override
public void validate(Object target, Errors errors) {
    try {
        UserBean user = (UserBean) target;
        if (user.getStdUsers().getUserName() == null) {
            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "stdUsers.userName", "user.name.empty");
            //errors.reject("stdUsers.userName", "User Name is mandatory");
        }
    } catch (Exception e) {
        System.out.println(e);
    }
}

} Bean Class-

public class UserBean {

private @Valid StdUsers stdUsers;
private @Valid StdCheckAccessV chkAccessV;
private boolean listView = true;
private String rePassword;

getters and setters.... }

index.jsp-

<body>
    <%
        session.setAttribute("id", 1);
        session.setAttribute("roleId", 1);
    %>
    <a href="User/allUsers.html">User</a><br>
</body>

CMN/STD100002.jsp page

<td class="tdright"><form:label path="stdUsers.userName">User Name<em>*</em></form:label></td>
                    <td><form:input path="stdUsers.userName"/></td>
                    <td><form:errors path="stdUsers.userName"></form:errors></td>
<a href="#" name="btnsub" id="btnsub" onclick="submitUser()">
                                <table cellspacing="0" cellpadding="0" border="0">
                                    <tr>
                                        <td width="25" height="24px" align="center">
                                            <img src="${pageContext.servletContext.contextPath}/resources/images/Buttons/gray icon/Add.png" width="16" height="15"  border="0" />
                                        </td>
                                        <td>Submit</td>
                                        <td></td>
                                    </tr>
                                </table>
                            </a>
        <script type="text/javascript">

        function submitUser(){
            document.form1.action="${pageContext.servletContext.contextPath}/User/submitUser";
            document.form1.submit();
        }

    </script>

I am following a tutorial for using validation in spring as i am new for spring. On click of the submit button while leaving the User Name field empty, it should get validated with the message from Validator. When i tried to print the error in controller class by-

System.out.println("result has errors   " + result.toString());

it prints-

result has errors   org.springframework.validation.BeanPropertyBindingResult: 1 errors

Please help, i am not getting where i am wrong.

I used this code to check where is the error-

for (Object object : result.getAllErrors()) {
            if (object instanceof FieldError) {
                FieldError fieldError = (FieldError) object;
                System.out.println("the field errors::::::::::::::::"+fieldError.getCode());
            }
            if (object instanceof ObjectError) {
                ObjectError objectError = (ObjectError) object;
                System.out.println("the object errors:::::::::"+objectError.getCode());
            }
        }

and i found-

the field errors::::::::::::::::user.name.empty
the object errors:::::::::user.name.empty
///////result has errors   org.springframework.validation.BeanPropertyBindingResult: 2       errors

Field error in object 'userSetup' on field 'stdUsers.userName': rejected value []; codes  [user.name.empty.userSetup.stdUsers.userName,user.name.empty.stdUsers.userName,user.name.em pty.userName,user.name.empty.java.lang.String,user.name.empty]; arguments []; default  message [null]

Since these two fields i am putting empty to check validation. If i will get these error on putting the fields empty then how can i validate them?

StdUser-

@Entity
@Table(name = "STD_USERS")
@NamedQueries({
@NamedQuery(name = "StdUsers.findAll", query = "SELECT s FROM StdUsers s")})
public class StdUsers implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GenericGenerator(name="generator",strategy="increment")
@GeneratedValue(generator="generator")
@Basic(optional = false)
@Column(name = "ID", nullable = false)
private Long id;
@Basic(optional = false)
@Column(name = "USER_NAME", nullable = false, length = 50)
private String userName;

setters and getters.....

Any one please reply.

回答1:

Oh finally got the solution just here- Changed the Validator class as-

try {
        UserBean user = (UserBean) target;

            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "stdUsers.userName","required.stdUsers.userName" ,"User name required");

    } catch (Exception e) {
        System.out.println(e);
    }

and in Controller class rather than returning to controller's allUsers method when result.hasError() i.e.-

return new ModelAndView("redirect:/User/allUsers");

changed to(navigated to page)-

return new ModelAndView("/CMN/STD100002");

and yes if you are getting date conversion related error, use this in your controller class-

@InitBinder
private void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");//edit for the    format you need
    dateFormat.setLenient(false);
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}