Example usage for org.springframework.web.bind ServletRequestDataBinder getBindingResult

List of usage examples for org.springframework.web.bind ServletRequestDataBinder getBindingResult

Introduction

In this page you can find the example usage for org.springframework.web.bind ServletRequestDataBinder getBindingResult.

Prototype

public BindingResult getBindingResult() 

Source Link

Document

Return the BindingResult instance created by this DataBinder.

Usage

From source file:org.bibsonomy.webapp.util.spring.controller.MinimalisticControllerSpringWrapper.java

/**
 * instantiates, initializes and runs the MinimalisticController
 * //from ww w.  jav a2  s. c om
 * @see org.springframework.web.servlet.mvc.AbstractController#handleRequestInternal(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 */
@SuppressWarnings("unchecked")
@Override
protected ModelAndView handleRequestInternal(final HttpServletRequest request,
        final HttpServletResponse response) throws Exception {
    ((RequestLogic) getApplicationContext().getBean("requestLogic")).setRequest(request); // hack but thats springs fault
    ((ResponseLogic) getApplicationContext().getBean("responseLogic")).setResponse(response); // hack but thats springs fault
    final MinimalisticController<T> controller = (MinimalisticController<T>) getApplicationContext()
            .getBean(controllerBeanName);
    /**
     * Controller is put into request.
     * 
     * FIXME: is this still neccessary?
     * 
     * SuppressValidation retrieves controller from request again!
     */
    request.setAttribute(CONTROLLER_ATTR_NAME, controller);

    /*
     * DEBUG: log request attributes
     */
    if (log.isDebugEnabled()) {
        final Enumeration<?> e = request.getAttributeNames();
        while (e.hasMoreElements()) {
            log.debug(e.nextElement().toString());
        }
    }

    final T command = controller.instantiateCommand();

    /*
     * put context into command
     * 
     * TODO: in the future this is hopefully no longer needed, since the wrapper
     * only exists to transfer request attributes into the command.
     */
    command.setContext((RequestWrapperContext) request.getAttribute(RequestWrapperContext.class.getName()));

    /*
     * set validator for this instance
     */
    if (controller instanceof ValidationAwareController<?>) {
        this.setValidator(((ValidationAwareController<T>) controller).getValidator());
    }

    /*
     * bind request attributes to command
     */
    final ServletRequestDataBinder binder = bindAndValidate(request, command);
    final BindException errors = new BindException(binder.getBindingResult());
    if (controller instanceof ErrorAware) {
        ((ErrorAware) controller).setErrors(errors);
    }

    View view;

    /*
     * define error view
     */
    if (controller instanceof AjaxController) {
        view = Views.AJAX_ERRORS;
    } else {
        view = Views.ERROR;
    }

    try {
        view = controller.workOn(command);
    } catch (final MalformedURLSchemeException malformed) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        errors.reject("error.http.notFound", malformed.getMessage());
        log.warn("Could not complete controller (invalid URL scheme) : " + malformed.getMessage());
    } catch (final AccessDeniedException ad) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        errors.reject(ad.getMessage());
        log.warn("Could not complete controller (AccessDeniedException), occured in: " + ad.getStackTrace()[0]
                + ", msg is: " + ad.getMessage());
    } catch (final ServiceUnavailableException e) {
        response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        response.setHeader("Retry-After", Long.toString(e.getRetryAfter()));
        errors.reject(e.getMessage(), new Object[] { e.getRetryAfter() }, "Service unavailable");
        /*
         *  this exception is only thrown in UserLoginController
         *  if desired, add some logging there. Otherwise, our error logs get
         *  cluttered.(dbe)
         */
        // log.warn("Could not complete controller (Service unavailable): " + e.getMessage());
    } catch (final ResourceMovedException e) {
        response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        response.setHeader("Location",
                urlGenerator.getPostUrl(e.getResourceType(), e.getNewIntraHash(), e.getUserName()));
    } catch (final ResourceNotFoundException e) {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        errors.reject("error.post.notfound", e.getMessage()); // FIXME: it would be better, to show the specific 404 view
    } catch (final org.springframework.security.access.AccessDeniedException ex) {
        /*
         * we rethrow the exception here in order that Spring Security can
         * handle the exception (saving request and redirecting to the login
         * page (if user is not logged in) or to the access denied page)
         */
        throw ex;
    } catch (final Exception ex) {
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        errors.reject("error.internal", new Object[] { ex }, "Internal Server Error: " + ex.getMessage());
        log.error("Could not complete controller (general exception) for request /" + request.getRequestURI()
                + "?" + request.getQueryString() + " with referer " + request.getHeader("Referer"), ex);
    }

    log.debug("Exception catching block passed, putting comand+errors into model.");

    final Map<String, Object> model = new HashMap<String, Object>();
    model.put(getCommandName(), command);

    /*
     * put errors into model 
     */
    model.putAll(errors.getModel());

    log.debug("Returning model and view.");

    /**
     * If the view is already a Spring view, use it directly.
     * The primal reason for the this workaround is, that Spring's RedirctView
     * automatically appends the model parameters to each redirected URL. This
     * can only be avoided by calling setExposeModelAttributes(false) on the 
     * RedirectView. Hence, we must directly create a redirect view instead of 
     * using a "redirect:..." URL.  
     */
    if (org.springframework.web.servlet.View.class.isAssignableFrom(view.getClass())) {
        return new ModelAndView((org.springframework.web.servlet.View) view, model);
    }

    return new ModelAndView(view.getName(), model);
}

From source file:org.gbif.portal.web.controller.registration.RegistrationController.java

/**
 * Ajax entry point that adds the resource to provider
 *//*from ww w. j  a v a2s.c o m*/
@SuppressWarnings("unchecked")
public ModelAndView addDataResource(HttpServletRequest request, HttpServletResponse response) throws Exception {
    logger.info("Adding a resource...");
    debugRequestParams(request);

    ResourceDetail resourceDetail = new ResourceDetail();
    ServletRequestDataBinder binder = createBinder(request, resourceDetail);
    binder.bind(request);
    BindingResult result = binder.getBindingResult();
    validateDataResource(resourceDetail, result);

    logger.info("Adding the resource: " + resourceDetail.getName());
    uddiUtils.updateResource(resourceDetail, request.getParameter("businessKey"));
    Map<String, Object> data = new HashMap<String, Object>();
    data.put(REQUEST_RESOURCE, resourceDetail);
    data.putAll(referenceDataForResourceList(request));
    return null;
}

From source file:org.gbif.portal.web.controller.registration.RegistrationController.java

/**
 * Updates details in UDDI for this dataset.
 * //from   w  w w .ja  v  a 2 s .co m
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
public ModelAndView completeManualRegistration(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    // bind to object
    ResourceDetail resource = new ResourceDetail();
    ServletRequestDataBinder binder = createBinder(request, resource);
    initBinder(request, binder);
    binder.bind(request);
    BindingResult result = binder.getBindingResult();
    validateDataResource(resource, result);
    logger.info("Adding the resource: " + resource.getName());

    if (result.hasErrors()) {
        logger.info("Errors have occurred: " + result);
        Map<String, Object> data = new HashMap<String, Object>();
        data.put(REQUEST_RESOURCE, resource);
        data.putAll(referenceDataForResourceList(request));
        data.put(BindingResult.MODEL_KEY_PREFIX + RegistrationController.REQUEST_RESOURCE, result);
        data.put("editableEndpoint", true);
        // put the errors in the request
        return new ModelAndView("registrationResourceManual", data);
    } else {
        String businessKey = request.getParameter("businessKey");
        uddiUtils.updateResource(resource, businessKey);
        return new ModelAndView(new RedirectView(
                request.getContextPath() + "/register/showDataResources?businessKey=" + businessKey));
    }
}

From source file:org.gbif.portal.web.controller.registration.RegistrationController.java

/**
 * Create a new user in LDAP.//from  www. j a v  a2s.c  om
 * 
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
public ModelAndView newUser(HttpServletRequest request, HttpServletResponse response) throws Exception {

    if (!isFormSubmission(request)) {
        ModelAndView mav = new ModelAndView("newUser");
        UserLogin ul = new UserLogin();
        mav.addObject("user", ul);
        return mav;
    }

    UserLogin ul = new UserLogin();
    ServletRequestDataBinder binder = createBinder(request, ul);
    binder.bind(request);
    BindingResult result = binder.getBindingResult();
    String systemUserName = getSystemUserName(ul.getUsername());
    String suggestedUsername = null;
    // validate
    if (StringUtils.isEmpty(ul.getUsername())) {
        result.rejectValue("username", ErrorMessageKeys.MUST_BE_SPECIFIED);
    } else if (ul.getUsername().length() < minimumUsernameLength) {
        result.rejectValue("username", ErrorMessageKeys.MUST_BE_MINIMIUM_LENGTH);
    } else if (!validateUsername(ul.getUsername())) {
        result.rejectValue("username", ErrorMessageKeys.CONTAINS_INVALID_CHARS);
    } else if (ldapUtils.userNameInUse(systemUserName)) {
        // iterate until a username available
        for (int i = 0; i < Integer.MAX_VALUE; i++) {
            suggestedUsername = getSystemUserName(ul.getUsername() + i);
            if (!ldapUtils.userNameInUse(suggestedUsername)) {
                break;
            }
        }
        result.rejectValue("username", ErrorMessageKeys.USERNAME_IN_USE);
    }

    if (StringUtils.isEmpty(ul.getFirstName())) {
        result.rejectValue("firstName", ErrorMessageKeys.MUST_BE_SPECIFIED);
    }
    if (StringUtils.isEmpty(ul.getSurname())) {
        result.rejectValue("surname", ErrorMessageKeys.MUST_BE_SPECIFIED);
    }

    if (!StringUtils.isEmpty(ul.getEmail())) {
        Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
        Matcher m = p.matcher(ul.getEmail());
        boolean validEmail = m.matches();
        if (!validEmail)
            result.rejectValue("email", ErrorMessageKeys.INVALID_VALUE);
    } else {
        result.rejectValue("email", ErrorMessageKeys.MUST_BE_SPECIFIED);
    }
    if (StringUtils.isEmpty(ul.getPassword())) {
        result.rejectValue("password", ErrorMessageKeys.MUST_BE_SPECIFIED);
    } else if (!validatePassword(ul.getPassword())) {
        result.rejectValue("password", ErrorMessageKeys.MUST_BE_MINIMIUM_LENGTH);
    }

    if (result.hasErrors()) {
        ModelAndView mav = new ModelAndView("newUser");
        if (suggestedUsername != null) {
            mav.addObject("suggestedUsername", suggestedUsername);
        }
        mav.addObject(BindingResult.MODEL_KEY_PREFIX + "user", result);
        return mav;
    }

    // send verification email
    SimpleMailMessage verificationMessage = new SimpleMailMessage(userTemplateMessage);
    verificationMessage.setTo(ul.getEmail());
    String encryptedPassword = passwordUtils.encryptPassword(ul.getPassword(), true);
    verificationMessage.setSubject("Confirm e-mail address for GBIF Data Portal");
    verificationMessage.setText("Please visit the following link to confirm your e-mail address:\n\n"
            + "http://" + request.getHeader("host") + request.getContextPath() + "/user/verification" + "?fn="
            + ul.getFirstName() + "&sn=" + ul.getSurname() + "&e=" + ul.getEmail() + "&u=" + ul.getUsername()
            + "&p=" + encryptedPassword);
    try {
        mailSender.send(verificationMessage);
    } catch (MailException e) {
        // simply log it and go on...
        logger.error("Couldn't send message", e);
        ModelAndView mav = new ModelAndView("registrationVerificationFailureView");
        mav.addObject("user", ul);
        return mav;
    }

    // successful
    ModelAndView mav = new ModelAndView("registrationVerificationSuccessView");
    mav.addObject("user", ul);
    return mav;
}

From source file:org.gbif.portal.web.controller.registration.RegistrationController.java

/**
 * Saves the values for the data provider
 *///from www . java  2 s .  c  o  m
@SuppressWarnings("unchecked")
public ModelAndView synchroniseProvider(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    ProviderDetail provider = new ProviderDetail();
    ServletRequestDataBinder binder = createBinder(request, provider);
    initBinder(request, binder);
    binder.bind(request);
    BindingResult result = binder.getBindingResult();
    validateDataProvider(provider, result);

    if (result.hasErrors()) {
        logger.info("Errors have occurred: " + result);
        Map<String, Object> data = new HashMap<String, Object>();
        // put the errors in the request
        data.put(BindingResult.MODEL_KEY_PREFIX + RegistrationController.REQUEST_PROVIDER_DETAIL, result);
        data.put(RegistrationController.REQUEST_CONTACT_TYPES, ProviderDetail.ContactTypes.values());
        data.put(RegistrationController.REQUEST_PROVIDER_DETAIL, result.getTarget());
        data.putAll(referenceDataForProvider(request));
        return new ModelAndView("registrationUpdateProviderDetail", data);
    } else {
        boolean success = synchroniseProvider(request, provider, result);
        if (!success) {
            return new ModelAndView("registrationUDDIFailure");
        }
        // return showDataResources(request, response, provider);
        return new ModelAndView(new RedirectView(request.getContextPath() + "/register/viewDataProvider?"
                + REQUEST_BUSINESS_UDDI_KEY + "=" + provider.getBusinessKey()));
    }
}

From source file:org.gbif.portal.web.controller.registration.RegistrationController.java

/**
 * This is the entry point for the AJAX call to update the resource
 *//*  w  ww. j  ava  2  s  . com*/
@SuppressWarnings("unchecked")
public ModelAndView updateDataResource(HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    logger.info("Updating a resource...");
    debugRequestParams(request);
    ResourceDetail resource = new ResourceDetail();
    ServletRequestDataBinder binder = createBinder(request, resource);
    binder.bind(request);
    String businessKey = request.getParameter(REQUEST_BUSINESS_UDDI_KEY);
    BindingResult result = binder.getBindingResult();
    validateDataResource(resource, result);

    if (result.getErrorCount() == 0) {
        // it is always the last one, due to the fact that only one is ever submitted
        // although it's id may be something other than 0
        if (logger.isDebugEnabled()) {
            logger.debug("Resource name: " + resource.getName());
            logger.debug("Resource description: " + resource.getDescription());
        }
        uddiUtils.updateResource(resource, request.getParameter(REQUEST_BUSINESS_UDDI_KEY));
        return new ModelAndView(new RedirectView(
                request.getContextPath() + "/register/showDataResources?businessKey=" + businessKey));
    } else {
        logger.error(result.getAllErrors());
        // put the errors in the request
        Map<String, Object> data = new HashMap<String, Object>();
        data.putAll(referenceDataForResource(request, resource));
        data.put(RegistrationController.REQUEST_RESOURCE, resource);
        data.put(BindingResult.MODEL_KEY_PREFIX + RegistrationController.REQUEST_RESOURCE, result);
        List<String> beanProperties = retrieveReadonlyPropertiesForResource(resource);
        data.putAll(referenceDataForResourceList(request));
        data.put("readonlyProperties", beanProperties);
        return new ModelAndView("registrationResourceDetail", data);
    }
}

From source file:org.nextframework.controller.MultiActionController.java

/**
 * Invokes the named method./*from  w w w.  j  a v  a 2 s .  c  o  m*/
 * <p>
 * Uses a custom exception handler if possible; otherwise, throw an
 * unchecked exception; wrap a checked exception or Throwable.
 * @param useCommand 
 */
@SuppressWarnings("deprecation")
protected final ModelAndView invokeNamedMethod(Method method, WebRequestContext request, Object useCommand)
        throws Exception {
    //TODO TRATAMENTO DE LOOP ETERNO (REFERENCIA CIRCULAR)

    do {
        Input input = null;
        boolean fromErrors = false;
        try {
            List<Object> params = new ArrayList<Object>(2);
            boolean hasRequestParameter = method.getParameterTypes().length > 0
                    && method.getParameterTypes()[0].isAssignableFrom(WebRequestContext.class)
                    && !method.getParameterTypes()[0].equals(Object.class);
            if (hasRequestParameter) {
                params.add(request);
            }

            if (useCommand == null) {
                input = getAnnotation(method, Input.class);//modificado em 22/10/2010, esse cdigo ficava dentro do if.. e s funcionava caso existissem commands
                if ((hasRequestParameter && method.getParameterTypes().length == 2)
                        || (!hasRequestParameter && method.getParameterTypes().length == 1)) {
                    Class<?> commandClass = getCommandClass(method, hasRequestParameter ? 1 : 0);
                    CommandInfo commandInfo = getCommandInfo(method);

                    Object command;
                    ServletRequestDataBinder binder;

                    if (!fromErrors) {
                        command = getCommandObject(request, commandClass, commandInfo);
                        binder = bind(request, command, commandInfo.validate);
                    } else {
                        command = getCommandObject(request, commandClass, commandInfo);
                        //se veio de erros nao fazer o bind novamente
                        binder = new ServletRequestDataBinder(command, getCommandName(command));
                    }

                    params.add(command);

                    if (binder.getBindingResult().hasErrors()) {
                        String inputAction = null;

                        if (input != null) {
                            inputAction = input.value();
                        } else {
                            logger.warn("No @Input specified for method " + method.getDeclaringClass().getName()
                                    + "." + method.getName() + ". Bind errors.");
                            new BindException(binder.getBindingResult()).printStackTrace();
                            if (commandInfo.session) {
                                //should reset the command
                                command = instantiateNewSessionCommand(request, commandClass,
                                        getSessionCommandName(commandClass, commandInfo));
                                inputAction = method.getName();
                            }
                        }
                        if (inputAction != null) {
                            ((DefaultWebRequestContext) request).setLastAction(inputAction);
                            Method handlerMethod = this.methodNameResolver.getHandlerMethod(inputAction);
                            ((DefaultWebRequestContext) request)
                                    .setBindException(new BindException(binder.getBindingResult()));
                            if (!handlerMethod.getName().equals(method.getName())) {
                                //o input deve ter o mesmo command do mtodo que declarou o input .. ento deixaremos o mtodo de input.. fazer o handling como o mesmo command
                                ((DefaultWebRequestContext) request)
                                        .setBindException(new BindException(binder.getBindingResult()));
                                method = handlerMethod;
                            }
                        } else {
                            binder.close();
                        }
                    }
                }
            } else {
                params.add(useCommand);
            }
            Object result = method.invoke(this.delegate, params.toArray(new Object[params.size()]));
            return convertActionResultToModelAndView(method, result);
        } catch (NoSuchRequestHandlingMethodException e) {
            throw e;
        } catch (NextException e) {
            throw e;
        } catch (InvocationTargetException ex) {
            // the invoked method threw exception
            if (input == null) {
                OnErrors onErrors = getAnnotation(method, OnErrors.class);
                if (onErrors != null) {
                    fromErrors = true;
                    ((DefaultWebRequestContext) request).setLastAction(onErrors.value());
                    Method methodErrors = this.methodNameResolver.getHandlerMethod(onErrors.value());
                    request.addError(ex.getTargetException());
                    logger.error("Erro ao invocar mtodo " + method.getName() + " da classe "
                            + this.getClass().getName() + ". Redirecionando para onErrors: " + onErrors.value(),
                            ex.getTargetException());
                    method = methodErrors;
                    continue;
                } else {
                    // nao tem input e no tem onerrors.. deixar a exceo vazar para algum handler se for o caso
                }
            } else {
                //se tem input.. redirecionar para input
                boolean sameMethod = false;
                String inputName = input.value();

                Method handlerMethod = this.methodNameResolver.getHandlerMethod(inputName);
                sameMethod = handlerMethod.getName().equals(method.getName());

                //   se for o mesmo mtodo.. deixar a excecao vazar (se mandar para o mtodo denovo vai dar loop eterno porque a excecao vai ocorrer novamente
                if (!sameMethod) {
                    // se nao for o mesmo mtodo.. redirecionar
                    // poderiamos mandar um flag j que o mtodo a ser invocado tem o mesmo command .. nesse caso economizariamos o bind
                    // mas vamos deixar fazer o bind novamente porque j pode ter ocorrido algum processamento que alterou os valores do command 
                    method = handlerMethod;
                    request.addError(ex.getTargetException());
                    ((DefaultWebRequestContext) request).setLastAction(inputName);
                    logger.error(
                            "Erro ao invocar mtodo " + method.getName() + " da classe "
                                    + this.getClass().getName() + ". Redirecionando para input: " + inputName,
                            ex.getTargetException());
                    continue;
                }
            }
            return handleException(request, ex.getTargetException());
        } catch (IllegalArgumentException ex) {
            throw new NextException(
                    "No foi possvel invocar o mtodo. Se estiver utilizando o mtodo continueToAction verifique se o mtodo que pede o redirecionamento e o mtodo de destino possuem a mesma classe de command",
                    ex);
        } catch (Exception ex) {
            // The binding process threw an exception.
            return handleException(request, ex);
        }
    } while (true);
}

From source file:org.nextframework.controller.MultiActionController.java

/**
 * Bind request parameters onto the given command bean
 * //from ww  w.  java 2s  .  c o  m
 * @param request
 *            request from which parameters will be bound
 * @param command
 *            command object, that must be a JavaBean
 * @throws Exception
 *             in case of invalid state or arguments
 */
@SuppressWarnings("deprecation")
protected ServletRequestDataBinder bind(WebRequestContext request, Object command, boolean validate)
        throws Exception {
    logger.debug("Binding request parameters onto MultiActionController command");

    ServletRequestDataBinder binder = createBinder(request.getServletRequest(), command,
            getCommandName(command));
    onCreateBinderForCommand(binder, command);
    if (command.getClass().equals(Object.class)) {
        return binder;
    }
    binder.bind(request.getServletRequest());
    onCommandBind(binder, command);

    if (validate) {
        validate(request, command, binder);
    }
    String acao = request.getParameter(ACTION_PARAMETER);
    customValidation(request, command, new BindException(binder.getBindingResult()), acao);
    onCommandValidation(binder, command);

    return binder;
}

From source file:org.nextframework.controller.MultiActionController.java

protected void validate(WebRequestContext request, Object command, ServletRequestDataBinder binder) {

    if (!suppressValidation(request, command)) {
        BindException errors = new BindException(binder.getBindingResult());
        if (request.getAttribute(NextCommonsMultipartResolver.MAXUPLOADEXCEEDED) != null) {
            errors.reject("", "O tamanho mximo de upload de arquivos (10M) foi excedido");
        }/*from   w  w  w. ja va  2s  .co  m*/
        ObjectAnnotationValidator objectAnnotationValidator = new ObjectAnnotationValidator(
                ServiceFactory.getService(ValidatorRegistry.class), request.getServletRequest());
        objectAnnotationValidator.validate(command, errors);
        String acao = request.getParameter(ACTION_PARAMETER);
        validate(command, errors, acao);
        if (this.validators != null) {
            for (int i = 0; i < this.validators.length; i++) {
                if (this.validators[i].supports(command.getClass())) {
                    ValidationUtils.invokeValidator(this.validators[i], command, errors);
                }
            }
        }
    }
}

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

/**
 * Show a new form. Prepares a backing object for the current form
 * and the given request, including checking its validity.
 * @param request current HTTP request//from  w  w  w .jav a2  s .  c om
 * @return the prepared form view
 * @throws Exception in case of an invalid new form object
 */
protected final ModelAndView showNewForm(HttpServletRequest request) throws Exception {
    logger.debug("Displaying new form");

    // Create form-backing object for new form.
    T formObject = formBackingObject(request);
    Assert.state(formObject != null, "Form object returned by formBackingObject() must not be null");

    // Bind without validation, to allow for prepopulating a form, and for
    // convenient error evaluation in views (on both first attempt and resubmit).
    ServletRequestDataBinder binder = createBinder(request, formObject);
    binder.bind(request);
    BindingResult bindingResult = binder.getBindingResult();
    onBind(request, formObject, bindingResult);

    return showForm(request, bindingResult);
}