Example usage for org.springframework.validation BindingResult getFieldErrors

List of usage examples for org.springframework.validation BindingResult getFieldErrors

Introduction

In this page you can find the example usage for org.springframework.validation BindingResult getFieldErrors.

Prototype

List<FieldError> getFieldErrors();

Source Link

Document

Get all errors associated with a field.

Usage

From source file:cs544.wamp_blog_engine.controller.UserController.java

@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String add(@Valid User user, BindingResult result, HttpSession session, RedirectAttributes flashAttr,
        @RequestParam("file") MultipartFile file) {
    String view = "redirect:/";
    System.out.println("userController Add");

    if (!result.hasErrors()) {
        try {/*from  ww  w  . jav  a 2 s  .  com*/
            user.setProfilepic(file.getBytes());
        } catch (IOException ex) {
            Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
        }
        userService.addUser(user);
        session.removeAttribute("credential");
        flashAttr.addFlashAttribute("successfulSignup",
                "User signed up succesfully. please  log in to proceed");
        User u = (User) session.getAttribute("loggedUser");
        if (u != null && u.getUserCredential().isAdmin()) {
            view = "redirect:/settings";
        }
    } else {
        for (FieldError err : result.getFieldErrors()) {
            System.out.println("Error:" + err.getField() + ":" + err.getDefaultMessage());
        }
        view = "addUser";
    }
    return view;
}

From source file:com.oak_yoga_studio.controller.FacultyController.java

@RequestMapping(value = "/updateFacultyProfile", method = RequestMethod.POST)
public String updateUser(@Valid Faculty facultyUpdate, BindingResult result, HttpSession session,
        RedirectAttributes flashAttr, @RequestParam("file") MultipartFile file) {
    String view = "redirect:/";

    if (!result.hasErrors()) {
        int Id = ((Faculty) session.getAttribute("loggedUser")).getId();
        Faculty faculty = facultyService.getFacultyById(Id);

        faculty.setFirstName(facultyUpdate.getFirstName());
        faculty.setLastName(facultyUpdate.getLastName());
        //System.out.println("Date of Birth" + customerUpdate.getDateOfBirth());
        //customer.setDateOfBirth(customerUpdate.getDateOfBirth());
        faculty.setEmail(facultyUpdate.getEmail());

        try {/*from w  w  w .java 2 s.  c  o  m*/
            System.out.println("Imageeeeeeeeeee - " + file.getBytes());
            if (file.getBytes().length != 0) {
                faculty.setProfilePicture(file.getBytes());
            }
        } catch (IOException ex) {

        }

        facultyService.updateFaculty(Id, faculty);
    } else {
        for (FieldError err : result.getFieldErrors()) {
            System.out.println(
                    "Error from UpdateProfileController " + err.getField() + ": " + err.getDefaultMessage());
        }
        System.out.println("err");
    }
    return "redirect:/facultyProfile";
}

From source file:com.oak_yoga_studio.controller.AdminController.java

@RequestMapping(value = "/addFaculty", method = RequestMethod.POST)
public String addFaculty(Faculty faculty, BindingResult result, HttpSession session,
        RedirectAttributes flashAttr, @RequestParam("file") MultipartFile file) {
    String view = "redirect:/viewFaculties";

    if (!result.hasErrors()) {
        try {//from   w  w  w . jav  a 2 s.  c om
            faculty.setProfilePicture(file.getBytes());
        } catch (IOException ex) {
            //Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
        }
        faculty.getCredential().setActive(false);
        faculty.setActive(false);
        facultyServcie.addFaculty(faculty);
        session.removeAttribute("credential");
        flashAttr.addFlashAttribute("successful registered",
                "Faculty signed up succesfully. please  log in to proceed"); //           Customer c=(Customer) session.getAttribute("loggedCustomer");

    } else {
        for (FieldError err : result.getFieldErrors()) {
            System.out.println("Error:" + err.getField() + ":" + err.getDefaultMessage());
        }
        view = "addFaculty";
    }
    return view;
}

From source file:com.google.ie.web.controller.ProjectCommentController.java

/**
 * Handles request to add comment on a Project.
 * //  w  ww. j a  v a2s.c  om
 * @param projectComment key of the Project on which the comment is to be
 *        added.
 * @param user the User object
 * @throws IOException
 */
@RequestMapping(value = "/postProjectComments", method = RequestMethod.POST)
public void postCommentOnProject(HttpServletRequest request, @ModelAttribute ProjectComment projectComment,
        BindingResult result, Map<String, Object> map, @RequestParam String recaptchaChallengeField,
        @RequestParam String recaptchaResponseField, HttpSession session) throws IOException {
    ViewStatus viewStatus = new ViewStatus();
    Boolean captchaValidation = reCaptchaUtility.verifyCaptcha(request.getRemoteAddr(), recaptchaChallengeField,
            recaptchaResponseField);
    /* call CommentValidator to validate input ProjectComment object */
    getCommentValidator().validate(projectComment, result);
    if (result.hasErrors() || !captchaValidation) {
        logger.warn("Comment object has " + result.getErrorCount() + " validation errors");
        viewStatus.setStatus(WebConstants.ERROR);
        /* Add a message if the captcha validation fails */
        if (!captchaValidation) {
            viewStatus.addMessage(WebConstants.CAPTCHA, WebConstants.CAPTCHA_MISMATCH);
        }
        /* Iterate the errors and add a message for each error */
        for (Iterator<FieldError> iterator = result.getFieldErrors().iterator(); iterator.hasNext();) {
            FieldError fieldError = iterator.next();
            viewStatus.addMessage(fieldError.getField(), fieldError.getDefaultMessage());
            logger.warn("Error found in field: " + fieldError.getField() + " Message :"
                    + fieldError.getDefaultMessage());
        }

    } else {
        User user = (User) session.getAttribute(WebConstants.USER);
        Comment comment = commentService.addComment(projectComment, user);
        if (comment != null) {
            viewStatus.setStatus(WebConstants.SUCCESS);
            viewStatus.addMessage(WebConstants.COMMENTS, WebConstants.COMMENT_SUCCESSFULL);
        } else {
            viewStatus.setStatus(WebConstants.ERROR);
            viewStatus.addMessage(WebConstants.COMMENTS, WebConstants.COMMENT_FAILED);
        }
    }
    map.remove("projectComment");
    map.put(WebConstants.VIEW_STATUS, viewStatus);
}

From source file:net.nicholaswilliams.java.teamcity.plugin.buildNumber.TestSharedBuildNumberController.java

@Test
public void testDoHandleAddBuildNumberPost02() throws IOException, ServletException {
    this.setUpSecurity();

    expect(this.request.getParameter("action")).andReturn("add");
    expect(this.request.getMethod()).andReturn("POST");
    expect(this.request.getParameter("name")).andReturn("Hello");
    expect(this.request.getParameter("description")).andReturn("This is a description.");
    expect(this.request.getParameter("format")).andReturn("1.0.0.{D}");
    expect(this.request.getParameter("dateFormat")).andReturn("Ym");
    expect(this.request.getParameter("counter")).andReturn("-16");

    replay(this.service, this.request, this.response);

    ModelAndView modelAndView = this.controller.doHandle(this.request, this.response);

    assertNotNull("The model and view should not be null.", modelAndView);
    assertEquals("The view is not correct.", "/plugin/" + testNum + "/jsp/addBuildNumber.jsp",
            modelAndView.getViewName());

    Map<String, Object> model = modelAndView.getModel();
    assertNotNull("The model should not be null.", model);

    Object object = model.get(BindingResult.MODEL_KEY_PREFIX + "sharedBuildNumberForm");
    assertNotNull("The binding result attribute should not be null.", object);
    assertTrue("The binding result attribute should be a binding result object.",
            object instanceof BindingResult);

    BindingResult result = (BindingResult) object;
    assertEquals("The binding result object name is not correct.", "sharedBuildNumberForm",
            result.getObjectName());//w w  w . ja  v  a 2 s .  c o m
    assertTrue("The binding result should have errors.", result.hasErrors());
    assertEquals("The binding result should have 2 errors.", 2, result.getErrorCount());

    List<FieldError> errors = result.getFieldErrors();
    assertNotNull("The list of errors should not be null.", errors);
    assertEquals("The list length is not correct.", 2, errors.size());
    assertEquals("The first error is not correct.", "counter", errors.get(0).getField());
    assertEquals("The first error has the wrong message.", "The counter must be a positive integer.",
            errors.get(0).getDefaultMessage());
    assertEquals("The second error is not correct.", "dateFormat", errors.get(1).getField());
    assertEquals("The second error has the wrong message.",
            "The date format must be at least 3 characters long.", errors.get(1).getDefaultMessage());

    object = model.get("sharedBuildNumberForm");
    assertNotNull("sharedBuildNumberForm should not be null.", object);
    assertTrue("sharedBuildNumberForm should be a SharedBuildNumber.", object instanceof SharedBuildNumber);

    SharedBuildNumber form = (SharedBuildNumber) object;
    assertEquals("The name is not correct.", "Hello", form.getName());
    assertEquals("The description is not correct.", "This is a description.", form.getDescription());
    assertEquals("The format is not correct.", "1.0.0.{D}", form.getFormat());
    assertEquals("The date format is not correct.", "Ym", form.getDateFormat());
    assertEquals("The counter is not correct.", 1, form.getCounter());
}

From source file:com.oak_yoga_studio.controller.CustomerController.java

@RequestMapping(value = "/updateProfile", method = RequestMethod.POST)
public String updateUser(@Valid Customer customerUpdate, BindingResult result, HttpSession session,
        RedirectAttributes flashAttr, @RequestParam("file") MultipartFile file) {
    String view = "redirect:/";

    if (!result.hasErrors()) {
        int Id = ((Customer) session.getAttribute("loggedUser")).getId();
        Customer customer = customerService.getCustomerById(Id);

        customer.setFirstName(customerUpdate.getFirstName());
        customer.setLastName(customerUpdate.getLastName());
        //System.out.println("Date of Birth" + customerUpdate.getDateOfBirth());
        //customer.setDateOfBirth(customerUpdate.getDateOfBirth());
        customer.setEmail(customerUpdate.getEmail());

        try {/*from w w  w .  j  av a 2  s . c  om*/

            if (file.getBytes().length != 0) {
                customer.setProfilePicture(file.getBytes());
            }
        } catch (IOException ex) {

        }

        customerService.updateCustomer(Id, customer);
    } else {
        for (FieldError err : result.getFieldErrors()) {
            System.out.println(
                    "Error from UpdateProfileController " + err.getField() + ": " + err.getDefaultMessage());
        }
        System.out.println("err");
    }
    return "redirect:/editProfile";
}

From source file:net.nicholaswilliams.java.teamcity.plugin.buildNumber.TestSharedBuildNumberController.java

@Test
public void testDoHandleAddBuildNumberPost01() throws IOException, ServletException {
    this.setUpSecurity();

    expect(this.request.getParameter("action")).andReturn("add");
    expect(this.request.getMethod()).andReturn("POST");
    expect(this.request.getParameter("name")).andReturn("help");
    expect(this.request.getParameter("description")).andReturn("");
    expect(this.request.getParameter("format")).andReturn("{0");
    expect(this.request.getParameter("dateFormat")).andReturn("Ym");
    expect(this.request.getParameter("counter")).andReturn("15.1");

    replay(this.service, this.request, this.response);

    ModelAndView modelAndView = this.controller.doHandle(this.request, this.response);

    assertNotNull("The model and view should not be null.", modelAndView);
    assertEquals("The view is not correct.", "/plugin/" + testNum + "/jsp/addBuildNumber.jsp",
            modelAndView.getViewName());

    Map<String, Object> model = modelAndView.getModel();
    assertNotNull("The model should not be null.", model);

    Object object = model.get(BindingResult.MODEL_KEY_PREFIX + "sharedBuildNumberForm");
    assertNotNull("The binding result attribute should not be null.", object);
    assertTrue("The binding result attribute should be a binding result object.",
            object instanceof BindingResult);

    BindingResult result = (BindingResult) object;
    assertEquals("The binding result object name is not correct.", "sharedBuildNumberForm",
            result.getObjectName());/*  w w w  .  j  a v a2  s  .  co m*/
    assertTrue("The binding result should have errors.", result.hasErrors());
    assertEquals("The binding result should have 3 errors.", 3, result.getErrorCount());

    List<FieldError> errors = result.getFieldErrors();
    assertNotNull("The list of errors should not be null.", errors);
    assertEquals("The list length is not correct.", 3, errors.size());
    assertEquals("The first error is not correct.", "counter", errors.get(0).getField());
    assertEquals("The first error has the wrong message.", "The counter must be a positive integer.",
            errors.get(0).getDefaultMessage());
    assertEquals("The second error is not correct.", "name", errors.get(1).getField());
    assertEquals("The second error has the wrong message.",
            "The name must be between 5 and 60 characters long.", errors.get(1).getDefaultMessage());
    assertEquals("The third error is not correct.", "format", errors.get(2).getField());
    assertEquals("The third error has the wrong message.",
            "The build number format must be at least 3 characters long.", errors.get(2).getDefaultMessage());

    object = model.get("sharedBuildNumberForm");
    assertNotNull("sharedBuildNumberForm should not be null.", object);
    assertTrue("sharedBuildNumberForm should be a SharedBuildNumber.", object instanceof SharedBuildNumber);

    SharedBuildNumber form = (SharedBuildNumber) object;
    assertEquals("The name is not correct.", "help", form.getName());
    assertEquals("The description is not correct.", "", form.getDescription());
    assertEquals("The format is not correct.", "{0", form.getFormat());
    assertEquals("The date format is not correct.", "Ym", form.getDateFormat());
    assertEquals("The counter is not correct.", 1, form.getCounter());
}

From source file:net.nicholaswilliams.java.teamcity.plugin.buildNumber.TestSharedBuildNumberController.java

@Test
public void testDoHandleEditBuildNumberPost03() throws IOException, ServletException {
    this.setUpSecurity();

    SharedBuildNumber originalNumber = new SharedBuildNumber(26);

    expect(this.request.getParameter("action")).andReturn("edit");
    expect(this.request.getMethod()).andReturn("POST");
    expect(this.request.getParameter("id")).andReturn("26");
    expect(this.service.getSharedBuildNumber(26)).andReturn(originalNumber);
    expect(this.request.getParameter("name")).andReturn("Hello");
    expect(this.request.getParameter("description")).andReturn("This is a description.");
    expect(this.request.getParameter("format")).andReturn("1.0.0.{D}");
    expect(this.request.getParameter("dateFormat")).andReturn("Ym");
    expect(this.request.getParameter("counter")).andReturn("-16");

    replay(this.service, this.request, this.response);

    ModelAndView modelAndView = this.controller.doHandle(this.request, this.response);

    assertNotNull("The model and view should not be null.", modelAndView);
    assertEquals("The view is not correct.", "/plugin/" + testNum + "/jsp/editBuildNumber.jsp",
            modelAndView.getViewName());

    Map<String, Object> model = modelAndView.getModel();
    assertNotNull("The model should not be null.", model);
    assertEquals("sbnParameterPrefix is not correct.", BuildNumberPropertiesProvider.PARAMETER_PREFIX,
            model.get("sbnParameterPrefix"));

    Object object = model.get(BindingResult.MODEL_KEY_PREFIX + "sharedBuildNumberForm");
    assertNotNull("The binding result attribute should not be null.", object);
    assertTrue("The binding result attribute should be a binding result object.",
            object instanceof BindingResult);

    BindingResult result = (BindingResult) object;
    assertEquals("The binding result object name is not correct.", "sharedBuildNumberForm",
            result.getObjectName());/*from ww  w .  j  a  v a2 s.  c  o m*/
    assertTrue("The binding result should have errors.", result.hasErrors());
    assertEquals("The binding result should have 2 errors.", 2, result.getErrorCount());

    List<FieldError> errors = result.getFieldErrors();
    assertNotNull("The list of errors should not be null.", errors);
    assertEquals("The list length is not correct.", 2, errors.size());
    assertEquals("The first error is not correct.", "counter", errors.get(0).getField());
    assertEquals("The first error has the wrong message.", "The counter must be a positive integer.",
            errors.get(0).getDefaultMessage());
    assertEquals("The second error is not correct.", "dateFormat", errors.get(1).getField());
    assertEquals("The second error has the wrong message.",
            "The date format must be at least 3 characters long.", errors.get(1).getDefaultMessage());

    object = model.get("sharedBuildNumberForm");
    assertNotNull("sharedBuildNumberForm should not be null.", object);
    assertTrue("sharedBuildNumberForm should be a SharedBuildNumber.", object instanceof SharedBuildNumber);

    SharedBuildNumber form = (SharedBuildNumber) object;
    assertEquals("The name is not correct.", "Hello", form.getName());
    assertEquals("The description is not correct.", "This is a description.", form.getDescription());
    assertEquals("The format is not correct.", "1.0.0.{D}", form.getFormat());
    assertEquals("The date format is not correct.", "Ym", form.getDateFormat());
    assertEquals("The counter is not correct.", 1, form.getCounter());
}

From source file:net.nicholaswilliams.java.teamcity.plugin.buildNumber.TestSharedBuildNumberController.java

@Test
public void testDoHandleEditBuildNumberPost02() throws IOException, ServletException {
    this.setUpSecurity();

    SharedBuildNumber originalNumber = new SharedBuildNumber(37);

    expect(this.request.getParameter("action")).andReturn("edit");
    expect(this.request.getMethod()).andReturn("POST");
    expect(this.request.getParameter("id")).andReturn("37");
    expect(this.service.getSharedBuildNumber(37)).andReturn(originalNumber);
    expect(this.request.getParameter("name")).andReturn("help");
    expect(this.request.getParameter("description")).andReturn("");
    expect(this.request.getParameter("format")).andReturn("{0");
    expect(this.request.getParameter("dateFormat")).andReturn("Ym");
    expect(this.request.getParameter("counter")).andReturn("15.1");

    replay(this.service, this.request, this.response);

    ModelAndView modelAndView = this.controller.doHandle(this.request, this.response);

    assertNotNull("The model and view should not be null.", modelAndView);
    assertEquals("The view is not correct.", "/plugin/" + testNum + "/jsp/editBuildNumber.jsp",
            modelAndView.getViewName());

    Map<String, Object> model = modelAndView.getModel();
    assertNotNull("The model should not be null.", model);
    assertEquals("sbnParameterPrefix is not correct.", BuildNumberPropertiesProvider.PARAMETER_PREFIX,
            model.get("sbnParameterPrefix"));

    Object object = model.get(BindingResult.MODEL_KEY_PREFIX + "sharedBuildNumberForm");
    assertNotNull("The binding result attribute should not be null.", object);
    assertTrue("The binding result attribute should be a binding result object.",
            object instanceof BindingResult);

    BindingResult result = (BindingResult) object;
    assertEquals("The binding result object name is not correct.", "sharedBuildNumberForm",
            result.getObjectName());/*w  ww. j  a  va 2 s .c o m*/
    assertTrue("The binding result should have errors.", result.hasErrors());
    assertEquals("The binding result should have 3 errors.", 3, result.getErrorCount());

    List<FieldError> errors = result.getFieldErrors();
    assertNotNull("The list of errors should not be null.", errors);
    assertEquals("The list length is not correct.", 3, errors.size());
    assertEquals("The first error is not correct.", "counter", errors.get(0).getField());
    assertEquals("The first error has the wrong message.", "The counter must be a positive integer.",
            errors.get(0).getDefaultMessage());
    assertEquals("The second error is not correct.", "name", errors.get(1).getField());
    assertEquals("The second error has the wrong message.",
            "The name must be between 5 and 60 characters long.", errors.get(1).getDefaultMessage());
    assertEquals("The third error is not correct.", "format", errors.get(2).getField());
    assertEquals("The third error has the wrong message.",
            "The build number format must be at least 3 characters long.", errors.get(2).getDefaultMessage());

    object = model.get("sharedBuildNumberForm");
    assertNotNull("sharedBuildNumberForm should not be null.", object);
    assertTrue("sharedBuildNumberForm should be a SharedBuildNumber.", object instanceof SharedBuildNumber);

    SharedBuildNumber form = (SharedBuildNumber) object;
    assertEquals("The name is not correct.", "help", form.getName());
    assertEquals("The description is not correct.", "", form.getDescription());
    assertEquals("The format is not correct.", "{0", form.getFormat());
    assertEquals("The date format is not correct.", "Ym", form.getDateFormat());
    assertEquals("The counter is not correct.", 1, form.getCounter());
}