Example usage for org.springframework.validation BindingResult getModel

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

Introduction

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

Prototype

Map<String, Object> getModel();

Source Link

Document

Return a model Map for the obtained state, exposing a BindingResult instance as ' #MODEL_KEY_PREFIX MODEL_KEY_PREFIX + objectName' and the object itself as 'objectName'.

Usage

From source file:org.orcid.frontend.web.controllers.RegistrationController.java

@RequestMapping(value = "/answer-security-question/{encryptedEmail}", method = RequestMethod.POST)
public ModelAndView submitSecurityAnswer(@PathVariable("encryptedEmail") String encryptedEmail,
        @Valid ChangeSecurityQuestionForm changeSecurityQuestionForm, BindingResult bindingResult,
        RedirectAttributes redirectAttributes) {

    PasswordResetToken passwordResetToken = buildResetTokenFromEncryptedLink(encryptedEmail);
    OrcidProfile retrievedProfile = orcidProfileManager
            .retrieveOrcidProfileByEmail(passwordResetToken.getEmail(), LoadOptions.INTERNAL_ONLY);

    if (bindingResult.hasErrors()) {
        ModelAndView errorView = buildAnswerSecurityQuestionView(encryptedEmail, redirectAttributes);
        errorView.addAllObjects(bindingResult.getModel());
        return errorView;
    }/*from  ww  w.  ja v  a2 s .com*/

    String securityAnswer = retrievedProfile.getSecurityQuestionAnswer();
    if (!changeSecurityQuestionForm.getSecurityQuestionAnswer().trim()
            .equalsIgnoreCase(securityAnswer.trim())) {
        ModelAndView errorView = buildAnswerSecurityQuestionView(encryptedEmail, redirectAttributes);
        errorView.addObject("securityQuestionIncorrect", true);
        return errorView;
    }
    // build password standalone view
    return new ModelAndView("redirect:/one-time-password/" + encryptedEmail);
}

From source file:org.orcid.frontend.web.controllers.RegistrationController.java

@RequestMapping(value = "/one-time-password/{encryptedEmail}", method = RequestMethod.POST)
public ModelAndView confirmPasswordOneTimeResetView(HttpServletRequest request, HttpServletResponse response,
        @PathVariable("encryptedEmail") String encryptedEmail,
        @Valid PasswordTypeAndConfirmForm passwordTypeAndConfirmForm, BindingResult bindingResult,
        RedirectAttributes redirectAttributes) {

    PasswordResetToken passwordResetToken = buildResetTokenFromEncryptedLink(encryptedEmail);
    if (isTokenExpired(passwordResetToken)) {
        redirectAttributes.addFlashAttribute("passwordResetLinkExpired", true);
        return new ModelAndView("redirect:/reset-password");
    }/* ww w  . java2 s .co  m*/

    if (bindingResult.hasErrors()) {
        ModelAndView errorView = buildPasswordOneTimeResetView(encryptedEmail);
        errorView.addAllObjects(bindingResult.getModel());
        return errorView;
    }

    OrcidProfile passwordOnlyProfileUpdate = orcidProfileManager
            .retrieveOrcidProfileByEmail(passwordResetToken.getEmail(), LoadOptions.INTERNAL_ONLY);
    passwordOnlyProfileUpdate.setPassword(passwordTypeAndConfirmForm.getPassword() == null ? null
            : passwordTypeAndConfirmForm.getPassword().getValue());
    return updatePasswordAndGoToAccountsPage(request, response, passwordOnlyProfileUpdate);
}

From source file:org.orcid.frontend.web.controllers.RegistrationController.java

@RequestMapping(value = "/reset-password-email/{encryptedEmail}", method = RequestMethod.POST)
public ModelAndView submitPasswordReset(HttpServletRequest request, HttpServletResponse response,
        @PathVariable("encryptedEmail") String encryptedEmail,
        @Valid OneTimeResetPasswordForm oneTimeResetPasswordForm, BindingResult bindingResult,
        RedirectAttributes redirectAttributes) {

    PasswordResetToken passwordResetToken = buildResetTokenFromEncryptedLink(encryptedEmail);
    // double check link not expired - someone could send a curl request..
    if (isTokenExpired(passwordResetToken)) {
        redirectAttributes.addFlashAttribute("passwordResetLinkExpired", true);
        return new ModelAndView("redirect:/reset-password");
    }/*w  ww . j a  va  2 s. c o m*/

    // validate the form and redirect back to the reset view
    if (bindingResult.hasErrors()) {
        ModelAndView errorView = buildPasswordScreenWithOptionalSecurityQuestion(oneTimeResetPasswordForm);
        errorView.addAllObjects(bindingResult.getModel());
        return errorView;

    }
    // update password, and optionally question and answer
    OrcidProfile profileToUpdate = orcidProfileManager
            .retrieveOrcidProfileByEmail(passwordResetToken.getEmail(), LoadOptions.INTERNAL_ONLY);
    profileToUpdate.setPassword(oneTimeResetPasswordForm.getPassword().getValue());
    if (oneTimeResetPasswordForm.isSecurityDetailsPopulated()) {
        profileToUpdate.getOrcidInternal().getSecurityDetails().setSecurityQuestionId(
                new SecurityQuestionId(oneTimeResetPasswordForm.getSecurityQuestionId()));
        profileToUpdate.setSecurityQuestionAnswer(oneTimeResetPasswordForm.getSecurityQuestionAnswer());
    }

    return updatePasswordAndGoToAccountsPage(request, response, profileToUpdate);

}

From source file:org.orcid.frontend.web.controllers.WorksUpdateController.java

/**
 * Helper for saving a work manually. Doesn't actually save the work!
 *///ww w  .j a va 2s  . c o  m
@RequestMapping(value = "/save-work-manually", method = RequestMethod.POST)
public ModelAndView saveWorkManually(HttpServletRequest request,
        @ModelAttribute("manualWork") @Valid CurrentWork manualWork, BindingResult bindingResult) {
    if (bindingResult.hasErrors()) {
        ModelAndView mav = new ModelAndView("manual_work_form_contents");
        mav.addAllObjects(bindingResult.getModel());
        return mav;
    }
    OrcidProfile currentUser = getCurrentUser().getEffectiveProfile();
    String currentUserOrcid = currentUser.getOrcid().getValue();
    CreditName currentUserCreditName = currentUser.getOrcidBio().getPersonalDetails().getCreditName();
    List<CurrentWorkContributor> currentWorkContributors = manualWork.getCurrentWorkContributors();
    if (currentWorkContributors != null) {
        for (CurrentWorkContributor currentWorkContributor : currentWorkContributors) {
            currentWorkContributor.setOrcid(currentUserOrcid);
            if (currentUserCreditName != null) {
                currentWorkContributor.setCreditName(currentUserCreditName.getContent());
            }
        }
    }
    CurrentWorksForm currentWorksForm = new CurrentWorksForm();
    List<CurrentWork> currentWorksList = new ArrayList<CurrentWork>(1);
    currentWorksForm.setCurrentWorks(currentWorksList);
    currentWorksList.add(manualWork);
    // Just contains the added work not all works in the current list!
    ModelAndView mav = new ModelAndView("current_works_list");
    mav.addObject("showPrivacy", false);
    mav.addObject(currentWorksForm);
    return mav;
}

From source file:org.springframework.web.method.annotation.ModelAttributeMethodProcessor.java

/**
 * Resolve the argument from the model or if not found instantiate it with
 * its default if it is available. The model attribute is then populated
 * with request values via data binding and optionally validated
 * if {@code @java.validation.Valid} is present on the argument.
 * @throws BindException if data binding and validation result in an error
 * and the next method parameter is not of type {@link Errors}
 * @throws Exception if WebDataBinder initialization fails
 *///  ww w. j a  v  a 2s. c  o  m
@Override
@Nullable
public final Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {

    Assert.state(mavContainer != null, "ModelAttributeMethodProcessor requires ModelAndViewContainer");
    Assert.state(binderFactory != null, "ModelAttributeMethodProcessor requires WebDataBinderFactory");

    String name = ModelFactory.getNameForParameter(parameter);
    ModelAttribute ann = parameter.getParameterAnnotation(ModelAttribute.class);
    if (ann != null) {
        mavContainer.setBinding(name, ann.binding());
    }

    Object attribute = null;
    BindingResult bindingResult = null;

    if (mavContainer.containsAttribute(name)) {
        attribute = mavContainer.getModel().get(name);
    } else {
        // Create attribute instance
        try {
            attribute = createAttribute(name, parameter, binderFactory, webRequest);
        } catch (BindException ex) {
            if (isBindExceptionRequired(parameter)) {
                // No BindingResult parameter -> fail with BindException
                throw ex;
            }
            // Otherwise, expose null/empty value and associated BindingResult
            if (parameter.getParameterType() == Optional.class) {
                attribute = Optional.empty();
            }
            bindingResult = ex.getBindingResult();
        }
    }

    if (bindingResult == null) {
        // Bean property binding and validation;
        // skipped in case of binding failure on construction.
        WebDataBinder binder = binderFactory.createBinder(webRequest, attribute, name);
        if (binder.getTarget() != null) {
            if (!mavContainer.isBindingDisabled(name)) {
                bindRequestParameters(binder, webRequest);
            }
            validateIfApplicable(binder, parameter);
            if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
                throw new BindException(binder.getBindingResult());
            }
        }
        // Value type adaptation, also covering java.util.Optional
        if (!parameter.getParameterType().isInstance(attribute)) {
            attribute = binder.convertIfNecessary(binder.getTarget(), parameter.getParameterType(), parameter);
        }
        bindingResult = binder.getBindingResult();
    }

    // Add resolved attribute and BindingResult at the end of the model
    Map<String, Object> bindingResultModel = bindingResult.getModel();
    mavContainer.removeAttributes(bindingResultModel);
    mavContainer.addAllAttributes(bindingResultModel);

    return attribute;
}

From source file:org.springframework.web.servlet.mvc.generic.GenericFormController.java

/**
 * Prepare model and view for the given form, including reference and errors,
 * adding a controller-specific control model.
 * <p>In session form mode: Re-puts the form object in the session when returning
 * to the form, as it has been removed by getCommand.
 * <p>Can be used in subclasses to redirect back to a specific form page.
 * @param request current HTTP request//from  w w  w  .  j av a  2 s. c  o  m
 * @param bindingResult validation errors holder
 * @return the prepared form view
 */
protected final ModelAndView showForm(HttpServletRequest request, BindingResult bindingResult) {
    // In session form mode, re-expose form object as HTTP session attribute.
    // Re-binding is necessary for proper state handling in a cluster,
    // to notify other nodes of changes in the form object.
    String formAttrName = getFormSessionAttributeName(request);
    if (logger.isDebugEnabled()) {
        logger.debug("Setting form session attribute [" + formAttrName + "] to: " + bindingResult.getTarget());
    }
    request.getSession().setAttribute(formAttrName, bindingResult.getTarget());

    // Fetch errors model as starting point, containing form object under
    // "formObjectName", and corresponding Errors instance under internal key.
    ModelMap model = new ModelMap().addAllAttributes(bindingResult.getModel());

    // Merge reference data into model, if any.
    populateModel(request, model, bindingResult);

    // Trigger rendering of the specified view, using the final model.
    return new ModelAndView(getFormView(request), model);
}

From source file:ubic.gemma.web.controller.common.description.bibref.PubMedQueryControllerImpl.java

@Override
@RequestMapping(method = RequestMethod.POST)
public ModelAndView onSubmit(HttpServletRequest request, PubMedSearchCommand command, BindingResult result,
        SessionStatus status) {// ww  w.ja va 2 s.c o  m

    // in the future we can search in other ways.
    String accession = command.getAccession();

    if (StringUtils.isBlank(accession)) {

        result.rejectValue("search", "errors.pubmed.noaccession", "Accession was missing");
        return new ModelAndView("bibRefSearch");
    }

    // first see if we already have it in the system.
    BibliographicReference bibRefFound = bibliographicReferenceService.findByExternalId(accession);
    if (bibRefFound != null) {
        request.setAttribute("existsInSystem", Boolean.TRUE);
        this.saveMessage(request, "bibliographicReference.alreadyInSystem", accession, "Already in Gemma");
    } else {
        request.setAttribute("existsInSystem", Boolean.FALSE);
        try {
            bibRefFound = this.pubMedXmlFetcher.retrieveByHTTP(Integer.parseInt(accession));

            if (bibRefFound == null) {
                log.debug(accession + " not found in NCBI");

                result.rejectValue("accession", "bibliographicReference.notfoundInNCBI", "Not found in NCBI");
                return new ModelAndView("bibRefSearch", result.getModel());
            }

            this.saveMessage(request, "bibliographicReference.found", accession, "Found");

        } catch (NumberFormatException e) {
            result.rejectValue("accession", "error.integer", "Not a number");
            return new ModelAndView("bibRefSearch", result.getModel());
        }
    }

    status.setComplete();
    return new ModelAndView("bibRefView").addObject("bibliographicReference", bibRefFound);
}