Search in sources :

Example 41 with BindingResult

use of org.springframework.validation.BindingResult in project spring-mvc-31-demo by rstoyanchev.

the class AccountControllerTests method testSaveFail.

@Test
public void testSaveFail() {
    Account account = new Account();
    BindingResult result = new BeanPropertyBindingResult(account, "account");
    AccountManager mgr = createMock(AccountManager.class);
    mgr.saveOrUpdate(account);
    replay(mgr);
    AccountController contrlr = new AccountController(mgr);
    String view = contrlr.save(account, result);
    assertEquals("redirect:accounts", view);
    verify(mgr);
}
Also used : Account(org.springframework.samples.mvc31.crudcontroller.Account) BindingResult(org.springframework.validation.BindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) StubAccountManager(org.springframework.samples.mvc31.crudcontroller.StubAccountManager) AccountManager(org.springframework.samples.mvc31.crudcontroller.AccountManager) AccountController(org.springframework.samples.mvc31.crudcontroller.AccountController) Test(org.junit.Test)

Example 42 with BindingResult

use of org.springframework.validation.BindingResult in project spring-framework by spring-projects.

the class MappingJackson2XmlViewTests method renderSimpleBeanWithJsonView.

@Test
public void renderSimpleBeanWithJsonView() throws Exception {
    Object bean = new TestBeanSimple();
    Map<String, Object> model = new HashMap<>();
    model.put("bindingResult", mock(BindingResult.class, "binding_result"));
    model.put("foo", bean);
    model.put(JsonView.class.getName(), MyJacksonView1.class);
    view.setUpdateContentLength(true);
    view.render(model, request, response);
    String content = response.getContentAsString();
    assertThat(content.length() > 0).isTrue();
    assertThat(response.getContentLength()).isEqualTo(content.length());
    assertThat(content.contains("foo")).isTrue();
    assertThat(content.contains("boo")).isFalse();
    assertThat(content.contains(JsonView.class.getName())).isFalse();
}
Also used : BindingResult(org.springframework.validation.BindingResult) HashMap(java.util.HashMap) JsonView(com.fasterxml.jackson.annotation.JsonView) ScriptableObject(org.mozilla.javascript.ScriptableObject) Test(org.junit.jupiter.api.Test)

Example 43 with BindingResult

use of org.springframework.validation.BindingResult in project spring-framework by spring-projects.

the class MappingJackson2XmlViewTests method renderSimpleMap.

@Test
public void renderSimpleMap() throws Exception {
    Map<String, Object> model = new HashMap<>();
    model.put("bindingResult", mock(BindingResult.class, "binding_result"));
    model.put("foo", "bar");
    view.setUpdateContentLength(true);
    view.render(model, request, response);
    assertThat(response.getHeader("Cache-Control")).isEqualTo("no-store");
    MediaType mediaType = MediaType.parseMediaType(response.getContentType());
    assertThat(mediaType.isCompatibleWith(MediaType.parseMediaType(MappingJackson2XmlView.DEFAULT_CONTENT_TYPE))).isTrue();
    String jsonResult = response.getContentAsString();
    assertThat(jsonResult.length() > 0).isTrue();
    assertThat(response.getContentLength()).isEqualTo(jsonResult.length());
    validateResult();
}
Also used : BindingResult(org.springframework.validation.BindingResult) HashMap(java.util.HashMap) MediaType(org.springframework.http.MediaType) ScriptableObject(org.mozilla.javascript.ScriptableObject) Test(org.junit.jupiter.api.Test)

Example 44 with BindingResult

use of org.springframework.validation.BindingResult in project spring-framework by spring-projects.

the class ModelAttributeMethodArgumentResolver method resolveArgument.

@Override
public Mono<Object> resolveArgument(MethodParameter parameter, BindingContext context, ServerWebExchange exchange) {
    ResolvableType type = ResolvableType.forMethodParameter(parameter);
    Class<?> resolvedType = type.resolve();
    ReactiveAdapter adapter = (resolvedType != null ? getAdapterRegistry().getAdapter(resolvedType) : null);
    ResolvableType valueType = (adapter != null ? type.getGeneric() : type);
    Assert.state(adapter == null || !adapter.isMultiValue(), () -> getClass().getSimpleName() + " does not support multi-value reactive type wrapper: " + parameter.getGenericParameterType());
    String name = ModelInitializer.getNameForParameter(parameter);
    Mono<?> valueMono = prepareAttributeMono(name, valueType, context, exchange);
    // unsafe(): we're intercepting, already serialized Publisher signals
    Sinks.One<BindingResult> bindingResultSink = Sinks.unsafe().one();
    Map<String, Object> model = context.getModel().asMap();
    model.put(BindingResult.MODEL_KEY_PREFIX + name, bindingResultSink.asMono());
    return valueMono.flatMap(value -> {
        WebExchangeDataBinder binder = context.createDataBinder(exchange, value, name);
        return (bindingDisabled(parameter) ? Mono.empty() : bindRequestParameters(binder, exchange)).doOnError(bindingResultSink::tryEmitError).doOnSuccess(aVoid -> {
            validateIfApplicable(binder, parameter);
            BindingResult bindingResult = binder.getBindingResult();
            model.put(BindingResult.MODEL_KEY_PREFIX + name, bindingResult);
            model.put(name, value);
            // Ignore result: serialized and buffered (should never fail)
            bindingResultSink.tryEmitValue(bindingResult);
        }).then(Mono.fromCallable(() -> {
            BindingResult errors = binder.getBindingResult();
            if (adapter != null) {
                return adapter.fromPublisher(errors.hasErrors() ? Mono.error(new WebExchangeBindException(parameter, errors)) : valueMono);
            } else {
                if (errors.hasErrors() && !hasErrorsArgument(parameter)) {
                    throw new WebExchangeBindException(parameter, errors);
                }
                return value;
            }
        }));
    });
}
Also used : Sinks(reactor.core.publisher.Sinks) Errors(org.springframework.validation.Errors) WebExchangeDataBinder(org.springframework.web.bind.support.WebExchangeDataBinder) BindingResult(org.springframework.validation.BindingResult) BindingContext(org.springframework.web.reactive.BindingContext) Constructor(java.lang.reflect.Constructor) ServerWebExchange(org.springframework.web.server.ServerWebExchange) HandlerMethodArgumentResolverSupport(org.springframework.web.reactive.result.method.HandlerMethodArgumentResolverSupport) Model(org.springframework.ui.Model) ModelAttribute(org.springframework.web.bind.annotation.ModelAttribute) Map(java.util.Map) MethodParameter(org.springframework.core.MethodParameter) Nullable(org.springframework.lang.Nullable) ResolvableType(org.springframework.core.ResolvableType) ReactiveAdapterRegistry(org.springframework.core.ReactiveAdapterRegistry) WebExchangeBindException(org.springframework.web.bind.support.WebExchangeBindException) ReactiveAdapter(org.springframework.core.ReactiveAdapter) ClassUtils(org.springframework.util.ClassUtils) ValidationAnnotationUtils(org.springframework.validation.annotation.ValidationAnnotationUtils) Mono(reactor.core.publisher.Mono) List(java.util.List) Annotation(java.lang.annotation.Annotation) Optional(java.util.Optional) BeanUtils(org.springframework.beans.BeanUtils) Assert(org.springframework.util.Assert) BindingResult(org.springframework.validation.BindingResult) Sinks(reactor.core.publisher.Sinks) WebExchangeDataBinder(org.springframework.web.bind.support.WebExchangeDataBinder) WebExchangeBindException(org.springframework.web.bind.support.WebExchangeBindException) ResolvableType(org.springframework.core.ResolvableType) ReactiveAdapter(org.springframework.core.ReactiveAdapter)

Example 45 with BindingResult

use of org.springframework.validation.BindingResult in project spring-framework by spring-projects.

the class ErrorsMethodArgumentResolverTests method resolve.

@Test
void resolve() {
    BindingResult bindingResult = createBindingResult(new Foo(), "foo");
    this.bindingContext.getModel().asMap().put(BindingResult.MODEL_KEY_PREFIX + "foo", bindingResult);
    MethodParameter parameter = this.testMethod.arg(Errors.class);
    Object actual = this.resolver.resolveArgument(parameter, this.bindingContext, this.exchange).block(Duration.ofMillis(5000));
    assertThat(actual).isSameAs(bindingResult);
}
Also used : BindingResult(org.springframework.validation.BindingResult) MethodParameter(org.springframework.core.MethodParameter) Test(org.junit.jupiter.api.Test)

Aggregations

BindingResult (org.springframework.validation.BindingResult)140 Test (org.junit.Test)28 Test (org.junit.jupiter.api.Test)27 List (java.util.List)23 BeanPropertyBindingResult (org.springframework.validation.BeanPropertyBindingResult)23 ExceptionHandler (org.springframework.web.bind.annotation.ExceptionHandler)23 ResponseEntity (org.springframework.http.ResponseEntity)20 MethodArgumentNotValidException (org.springframework.web.bind.MethodArgumentNotValidException)20 Collectors (java.util.stream.Collectors)18 HttpServletRequest (javax.servlet.http.HttpServletRequest)18 FieldError (org.springframework.validation.FieldError)16 ObjectError (org.springframework.validation.ObjectError)16 Model (org.springframework.ui.Model)15 ControllerAdvice (org.springframework.web.bind.annotation.ControllerAdvice)14 HashMap (java.util.HashMap)13 Nonnull (javax.annotation.Nonnull)13 Nullable (javax.annotation.Nullable)13 NativeWebRequest (org.springframework.web.context.request.NativeWebRequest)13 DefaultProblem (org.zalando.problem.DefaultProblem)13 Problem (org.zalando.problem.Problem)13