Example usage for org.springframework.validation FieldError getField

List of usage examples for org.springframework.validation FieldError getField

Introduction

In this page you can find the example usage for org.springframework.validation FieldError getField.

Prototype

public String getField() 

Source Link

Document

Return the affected field of the object.

Usage

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

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

    if (!result.hasErrors()) {
        try {//from www.  j  a va2  s  .  c om
            customer.setProfilePicture(file.getBytes());
        } catch (IOException ex) {
            Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex);
        }
        customerService.addCustomer(customer);
        session.removeAttribute("credential");
        flashAttr.addFlashAttribute("successfulSignup",
                "Customer signed up succesfully. please  log in to proceed");

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

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

@RequestMapping(value = "/updateAddress", method = RequestMethod.POST)
public String updateAddress(@Valid Address addressUpdate, BindingResult result, HttpSession session,
        RedirectAttributes flashAttr) {/* w  w w.  ja  v a2s.c o m*/
    String view = "redirect:/";

    if (!result.hasErrors()) {
        int Id = ((Customer) session.getAttribute("loggedUser")).getId();
        Address address = customerService.getCutomerAdress(Id);

        address.setStreet(addressUpdate.getStreet());
        address.setCity(addressUpdate.getCity());
        address.setZipCode(addressUpdate.getZipCode());
        address.setState(addressUpdate.getState());
        if (address.getId() == 0) {
            addressService.addAddress(address);
        } else {
            addressService.updateAddress(address);
        }
    } 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: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 {/* w ww . j  a  va2s  .c  o m*/

            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:com.iflytek.edu.cloud.frame.spring.DefaultHandlerExceptionResolver.java

/**
 * ??//from   www.j a v a2s  .c  om
 *
 * @param allErrors
 * @param locale
 * @param subErrorType
 * @return
 */
private MainError getBusinessParameterMainError(List<ObjectError> allErrors, Locale locale,
        SubErrorType subErrorType) {
    MainError mainError = SubErrors.getMainError(subErrorType, locale);
    for (ObjectError objectError : allErrors) {
        if (objectError instanceof FieldError) {
            FieldError fieldError = (FieldError) objectError;
            SubErrorType tempSubErrorType = INVALIDE_CONSTRAINT_SUBERROR_MAPPINGS.get(fieldError.getCode());
            if (tempSubErrorType == subErrorType) {
                SubError subError = SubErrors.getSubError(tempSubErrorType.value(), locale,
                        fieldError.getField(), fieldError.getRejectedValue(), fieldError.getDefaultMessage());
                mainError.addSubError(subError);
            }
        }
    }
    return mainError;
}

From source file:com.ignou.aadhar.controllers.CitizenController.java

@RequestMapping(value = "/create", method = RequestMethod.POST)
public String createCitizen(@Valid Citizen newCitizen, BindingResult result, Model model) throws Exception {

    /* Check if there was any error while binding the citizen object */
    if (result.hasErrors()) {

        /* There was some error while binding the form data to java objects.
         * Lets re-direct the user back to the form.
         */// www  .  java 2s  .c  om
        for (FieldError error : result.getFieldErrors()) {
            System.out.println("--> " + error.getField() + " - " + error.getDefaultMessage());
        }

        model.addAttribute("newCitizen", newCitizen);
        model.addAttribute("genders", citizenService.getGenders());
        model.addAttribute("banks", bankService.list());
        model.addAttribute("accessRoles", citizenService.getAccessRoles());
        model.addAttribute("states", stateService.list());

        return "citizen/create";
    }

    /* Let's generate the UID for this citizen */
    newCitizen.setUid(UIDGenerator.generateUID(UIDTypes.CITIZEN));

    /* Also, set the created date for now's date */
    newCitizen.setCreated(new Date());

    /* During registration, the status would be pending */
    newCitizen.setStatus(UIDStates.PENDING.getCode());

    /* No error while binding the form data to java objects */
    /* Lets save the new Citizen into the database */
    Citizen dbCitizen = createCitizenDetails(newCitizen);

    try {
        EmailSender emailSender = new EmailSender();
        emailSender.send("justdpk@gmail.com", "Registration Successful", "UID Registration Successful.");
    } catch (Exception e) {
        e.printStackTrace();
    }

    /* Citizen added successfully. Lets re-direct to view page */
    return "redirect:/citizen/" + dbCitizen.getId();
}

From source file:org.jasig.schedassist.web.register.Registration.java

/**
 * Validate after the preferences related fields have been set.
 * //from  w w  w.ja v  a 2  s  .  c om
 * Delegates to a {@link PreferencesFormBackingObjectValidator}.
 * @param context
 */
public void validateSetPreferences(final ValidationContext context) {
    MessageContext messages = context.getMessageContext();

    PreferencesFormBackingObject command = this.toPreferencesFormBackingObject();

    BeanPropertyBindingResult errors = new BeanPropertyBindingResult(command, "registration");
    preferencesValidator.validate(command, errors);

    if (errors.hasErrors()) {
        for (FieldError error : errors.getFieldErrors()) {
            messages.addMessage(new MessageBuilder().error().source(error.getField())
                    .defaultText(error.getDefaultMessage()).build());
        }
    }
}

From source file:org.jasig.schedassist.web.register.Registration.java

/**
 * Validate schedule related fields./*from  ww  w.  j ava  2s.c  o  m*/
 * 
 * Delegates to a {@link BlockBuilderFormBackingObject}.
 * @param context
 */
public void validateSetSchedule(final ValidationContext context) {
    MessageContext messages = context.getMessageContext();

    BlockBuilderFormBackingObject command = this.toBlockBuilderFormBackingObject();
    BlockBuilderFormBackingObjectValidator validator = new BlockBuilderFormBackingObjectValidator();
    BeanPropertyBindingResult errors = new BeanPropertyBindingResult(command, "registration");
    validator.validate(command, errors);

    if (errors.hasErrors()) {
        for (FieldError error : errors.getFieldErrors()) {
            messages.addMessage(new MessageBuilder().error().source(error.getField())
                    .defaultText(error.getDefaultMessage()).build());
        }
    } else {
        this.scheduleSet = true;
    }
}

From source file:org.sakaiproject.metaobj.shared.control.XsltArtifactView.java

protected Source createXsltSource(Map map, String string, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws Exception {

    httpServletResponse.setContentType(getContentType());
    WebApplicationContext context = getWebApplicationContext();
    setUriResolver((URIResolver) context.getBean(uriResolverBeanName));

    ToolSession toolSession = SessionManager.getCurrentToolSession();

    String homeType = null;//w  w  w .  j  ava2s  .co  m

    ElementBean bean = (ElementBean) map.get("bean");

    Element root = null;
    Map paramsMap = new Hashtable();

    for (Enumeration e = httpServletRequest.getParameterNames(); e.hasMoreElements();) {
        String k = e.nextElement().toString();
        // Do not allow reserved parameter names to be overwritten
        if (!reservedParams.contains(k)) {
            paramsMap.put(k, httpServletRequest.getParameter(k));
        }
    }

    httpServletRequest.setAttribute(STYLESHEET_PARAMS, paramsMap);
    if (toolSession.getAttribute(FormHelper.PREVIEW_HOME_TAG) != null) {
        paramsMap.put("preview", "true");
    }

    if (toolSession.getAttribute(ResourceToolAction.ACTION_PIPE) != null) {
        paramsMap.put("fromResources", "true");
    }

    if (httpServletRequest.getAttribute(FormHelper.URL_DECORATION) != null) {
        paramsMap.put("urlDecoration", httpServletRequest.getAttribute(FormHelper.URL_DECORATION));
    }

    HashMap<String, String> xslParams = new HashMap<String, String>();
    xslParams.put(FormHelper.XSL_PRESENTATION_ID, FormHelper.PRESENTATION_ID);
    xslParams.put(FormHelper.XSL_PRESENTATION_TYPE, FormHelper.PRESENTATION_TEMPLATE_ID);
    xslParams.put(FormHelper.XSL_PRESENTATION_ITEM_ID, FormHelper.PRESENTATION_ITEM_DEF_ID);
    xslParams.put(FormHelper.XSL_PRESENTATION_ITEM_NAME, FormHelper.PRESENTATION_ITEM_DEF_NAME);
    xslParams.put(FormHelper.XSL_FORM_TYPE, ResourceEditingHelper.CREATE_SUB_TYPE);
    xslParams.put(FormHelper.XSL_ARTIFACT_REFERENCE, ResourceEditingHelper.ATTACHMENT_ID);
    xslParams.put(FormHelper.XSL_OBJECT_ID, FormHelper.XSL_OBJECT_ID);
    xslParams.put(FormHelper.XSL_OBJECT_TITLE, FormHelper.XSL_OBJECT_TITLE);
    xslParams.put(FormHelper.XSL_WIZARD_PAGE_ID, FormHelper.XSL_WIZARD_PAGE_ID);

    // Load up our XSL parameters according to the mapping into the tool session above.
    // Note that this is not always one-to-one due to some string/key inconsistencies around the tools.
    for (Entry<String, String> item : xslParams.entrySet()) {
        Object val = toolSession.getAttribute(item.getValue());
        if (val != null) {
            paramsMap.put(item.getKey(), val);
        }
    }

    Id id = null;

    if (bean instanceof Artifact) {
        root = getStructuredArtifactDefinitionManager().createFormViewXml((Artifact) bean, null);
        homeType = getHomeType((Artifact) bean);
        id = ((Artifact) bean).getId();
    } else {
        EditedArtifactStorage sessionBean = (EditedArtifactStorage) httpServletRequest.getSession()
                .getAttribute(EditedArtifactStorage.EDITED_ARTIFACT_STORAGE_SESSION_KEY);

        if (sessionBean != null) {
            root = getStructuredArtifactDefinitionManager()
                    .createFormViewXml((Artifact) sessionBean.getRootArtifact(), null);

            replaceNodes(root, bean, sessionBean);
            paramsMap.put("subForm", "true");
            homeType = getHomeType(sessionBean.getRootArtifact());
            id = sessionBean.getRootArtifact().getId();
        } else {
            return new javax.xml.transform.dom.DOMSource();
        }
    }

    if (id != null) {
        paramsMap.put("edit", "true");
        paramsMap.put(FormHelper.XSL_ARTIFACT_ID, id.getValue());
    }

    httpServletRequest.setAttribute(STYLESHEET_LOCATION,
            getStructuredArtifactDefinitionManager().getTransformer(homeType, readOnly));

    Errors errors = BindingResultUtils.getBindingResult(map, "bean");
    if (errors != null && errors.hasErrors()) {
        Element errorsElement = new Element("errors");

        List errorsList = errors.getAllErrors();

        for (Iterator i = errorsList.iterator(); i.hasNext();) {
            Element errorElement = new Element("error");
            ObjectError error = (ObjectError) i.next();
            if (error instanceof FieldError) {
                FieldError fieldError = (FieldError) error;
                errorElement.setAttribute("field", fieldError.getField());
                Element rejectedValue = new Element("rejectedValue");
                if (fieldError.getRejectedValue() != null) {
                    rejectedValue.addContent(fieldError.getRejectedValue().toString());
                }
                errorElement.addContent(rejectedValue);
            }
            Element message = new Element("message");
            message.addContent(context.getMessage(error, getResourceLoader().getLocale()));
            errorElement.addContent(message);
            errorsElement.addContent(errorElement);
        }

        root.addContent(errorsElement);
    }

    if (httpServletRequest.getParameter("success") != null) {
        Element success = new Element("success");
        success.setAttribute("messageKey", httpServletRequest.getParameter("success"));
        root.addContent(success);
    }

    if (toolSession.getAttribute(ResourceEditingHelper.CUSTOM_CSS) != null) {
        Element uri = new Element("uri");
        uri.setText((String) toolSession.getAttribute(ResourceEditingHelper.CUSTOM_CSS));
        root.getChild("css").addContent(uri);
        uri.setAttribute("order", "100");
    }

    if (toolSession.getAttribute(FormHelper.FORM_STYLES) != null) {
        List styles = (List) toolSession.getAttribute(FormHelper.FORM_STYLES);
        int index = 101;
        for (Iterator<String> i = styles.iterator(); i.hasNext();) {
            Element uri = new Element("uri");
            uri.setText(i.next());
            root.getChild("css").addContent(uri);
            uri.setAttribute("order", "" + index);
            index++;
        }
    }

    Document doc = new Document(root);
    return new JDOMSource(doc);
}

From source file:ch.ralscha.extdirectspring.bean.ExtDirectFormPostResult.java

private void addErrors(Locale locale, MessageSource messageSource, BindingResult bindingResult) {
    if (bindingResult != null && bindingResult.hasFieldErrors()) {
        Map<String, String> errorMap = new HashMap<String, String>();
        for (ObjectError objectError : bindingResult.getAllErrors()) {
            FieldError fieldError = (FieldError) objectError;
            String message = null;
            for (String code : fieldError.getCodes()) {
                message = MessageUtil.getMessage(code, null, locale); // , new Object[] {(fieldError.getObjectName() +"." + fieldError.getField()), fieldError.getRejectedValue()}
                if (StringUtils.isNotBlank(message)) {
                    break;
                }//from   ww  w .j  ava 2 s .c om
            }
            errorMap.put(fieldError.getField(),
                    StringUtils.defaultIfBlank(message, fieldError.getDefaultMessage()));
        }
        if (errorMap.isEmpty()) {
            addResultProperty("success", true);
        } else {
            addResultProperty("errors", errorMap);
            addResultProperty("success", false);
        }
    } else {
        setSuccess(true);
    }

    //        if (bindingResult != null && bindingResult.hasFieldErrors()) {
    //            Map<String, List<String>> errorMap = new HashMap<String, List<String>>();
    //            for (FieldError fieldError : bindingResult.getFieldErrors()) {
    //                String message = fieldError.getDefaultMessage();
    //                if (messageSource != null) {
    //                    Locale loc = (locale != null ? locale : Locale.getDefault());
    //                    message = messageSource.getMessage(fieldError.getCode(), fieldError.getArguments(), loc);
    //                }
    //                List<String> fieldErrors = errorMap.get(fieldError.getField());
    //
    //                if (fieldErrors == null) {
    //                    fieldErrors = new ArrayList<String>();
    //                    errorMap.put(fieldError.getField(), fieldErrors);
    //                }
    //
    //                fieldErrors.add(message);
    //            }
    //            if (errorMap.isEmpty()) {
    //                addResultProperty("success", true);
    //            } else {
    //                addResultProperty("errors", errorMap);
    //                addResultProperty("success", false);
    //            }
    //        } else {
    //            setSuccess(true);
    //        }
}