Search in sources :

Example 6 with AbstractHandlerMapping

use of org.springframework.web.servlet.handler.AbstractHandlerMapping in project spring-framework by spring-projects.

the class WebMvcConfigurationSupportExtensionTests method handlerMappings.

@Test
public void handlerMappings() throws Exception {
    RequestMappingHandlerMapping rmHandlerMapping = this.config.requestMappingHandlerMapping(this.config.mvcContentNegotiationManager(), this.config.mvcConversionService(), this.config.mvcResourceUrlProvider());
    rmHandlerMapping.setApplicationContext(this.context);
    rmHandlerMapping.afterPropertiesSet();
    assertThat(rmHandlerMapping.getUrlPathHelper().getClass()).isEqualTo(TestPathHelper.class);
    assertThat(rmHandlerMapping.getPathMatcher().getClass()).isEqualTo(TestPathMatcher.class);
    HandlerExecutionChain chain = rmHandlerMapping.getHandler(new MockHttpServletRequest("GET", "/"));
    assertThat(chain).isNotNull();
    HandlerInterceptor[] interceptors = chain.getInterceptors();
    assertThat(interceptors).isNotNull();
    assertThat(interceptors.length).isEqualTo(4);
    assertThat(interceptors[0].getClass().getSimpleName()).isEqualTo("CorsInterceptor");
    assertThat(interceptors[1].getClass()).isEqualTo(LocaleChangeInterceptor.class);
    assertThat(interceptors[2].getClass()).isEqualTo(ConversionServiceExposingInterceptor.class);
    assertThat(interceptors[3].getClass()).isEqualTo(ResourceUrlProviderExposingInterceptor.class);
    Map<RequestMappingInfo, HandlerMethod> map = rmHandlerMapping.getHandlerMethods();
    assertThat(map.size()).isEqualTo(2);
    RequestMappingInfo info = map.entrySet().stream().filter(entry -> entry.getValue().getBeanType().equals(UserController.class)).findFirst().orElseThrow(() -> new AssertionError("UserController bean not found")).getKey();
    assertThat(info.getPatternValues()).isEqualTo(Collections.singleton("/api/user/{id}"));
    AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping) this.config.viewControllerHandlerMapping(this.config.mvcConversionService(), this.config.mvcResourceUrlProvider());
    handlerMapping.setApplicationContext(this.context);
    assertThat(handlerMapping).isNotNull();
    assertThat(handlerMapping.getOrder()).isEqualTo(1);
    assertThat(handlerMapping.getUrlPathHelper().getClass()).isEqualTo(TestPathHelper.class);
    assertThat(handlerMapping.getPathMatcher().getClass()).isEqualTo(TestPathMatcher.class);
    chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/path"));
    assertThat(chain).isNotNull();
    assertThat(chain.getHandler()).isNotNull();
    chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/bad"));
    assertThat(chain).isNotNull();
    assertThat(chain.getHandler()).isNotNull();
    chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/old"));
    assertThat(chain).isNotNull();
    assertThat(chain.getHandler()).isNotNull();
    handlerMapping = (AbstractHandlerMapping) this.config.resourceHandlerMapping(this.config.mvcContentNegotiationManager(), this.config.mvcConversionService(), this.config.mvcResourceUrlProvider());
    handlerMapping.setApplicationContext(this.context);
    assertThat(handlerMapping).isNotNull();
    assertThat(handlerMapping.getOrder()).isEqualTo((Integer.MAX_VALUE - 1));
    assertThat(handlerMapping.getUrlPathHelper().getClass()).isEqualTo(TestPathHelper.class);
    assertThat(handlerMapping.getPathMatcher().getClass()).isEqualTo(TestPathMatcher.class);
    chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/resources/foo.gif"));
    assertThat(chain).isNotNull();
    assertThat(chain.getHandler()).isNotNull();
    interceptors = chain.getInterceptors();
    assertThat(interceptors.length).as(Arrays.toString(interceptors)).isEqualTo(5);
    assertThat(interceptors[0].getClass().getSimpleName()).isEqualTo("CorsInterceptor");
    // PathExposingHandlerInterceptor at interceptors[1]
    assertThat(interceptors[2].getClass()).isEqualTo(LocaleChangeInterceptor.class);
    assertThat(interceptors[3].getClass()).isEqualTo(ConversionServiceExposingInterceptor.class);
    assertThat(interceptors[4].getClass()).isEqualTo(ResourceUrlProviderExposingInterceptor.class);
    handlerMapping = (AbstractHandlerMapping) this.config.defaultServletHandlerMapping();
    handlerMapping.setApplicationContext(this.context);
    assertThat(handlerMapping).isNotNull();
    assertThat(handlerMapping.getOrder()).isEqualTo(Integer.MAX_VALUE);
    chain = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/anyPath"));
    assertThat(chain).isNotNull();
    assertThat(chain.getHandler()).isNotNull();
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) DEFAULT_VIEW_INCLUSION(com.fasterxml.jackson.databind.MapperFeature.DEFAULT_VIEW_INCLUSION) Validator(org.springframework.validation.Validator) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) StaticWebApplicationContext(org.springframework.web.context.support.StaticWebApplicationContext) HandlerExecutionChain(org.springframework.web.servlet.HandlerExecutionChain) APPLICATION_XML(org.springframework.http.MediaType.APPLICATION_XML) NativeWebRequest(org.springframework.web.context.request.NativeWebRequest) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) HandlerMethod(org.springframework.web.method.HandlerMethod) FAIL_ON_UNKNOWN_PROPERTIES(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) HandlerExceptionResolverComposite(org.springframework.web.servlet.handler.HandlerExceptionResolverComposite) BOOLEAN(org.assertj.core.api.InstanceOfAssertFactories.BOOLEAN) Map(java.util.Map) TestBean(org.springframework.beans.testfixture.beans.TestBean) AntPathMatcher(org.springframework.util.AntPathMatcher) SimpleUrlHandlerMapping(org.springframework.web.servlet.handler.SimpleUrlHandlerMapping) ContentNegotiatingViewResolver(org.springframework.web.servlet.view.ContentNegotiatingViewResolver) FormatterRegistry(org.springframework.format.FormatterRegistry) HandlerMethodArgumentResolver(org.springframework.web.method.support.HandlerMethodArgumentResolver) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) ConfigurableWebBindingInitializer(org.springframework.web.bind.support.ConfigurableWebBindingInitializer) RestController(org.springframework.web.bind.annotation.RestController) StringHttpMessageConverter(org.springframework.http.converter.StringHttpMessageConverter) Test(org.junit.jupiter.api.Test) List(java.util.List) DefaultMessageCodesResolver(org.springframework.validation.DefaultMessageCodesResolver) LocaleChangeInterceptor(org.springframework.web.servlet.i18n.LocaleChangeInterceptor) Principal(java.security.Principal) HandlerExceptionResolver(org.springframework.web.servlet.HandlerExceptionResolver) DeferredResultProcessingInterceptor(org.springframework.web.context.request.async.DeferredResultProcessingInterceptor) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) ConcurrentTaskExecutor(org.springframework.scheduling.concurrent.ConcurrentTaskExecutor) RequestMappingHandlerMapping(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping) ConversionServiceExposingInterceptor(org.springframework.web.servlet.handler.ConversionServiceExposingInterceptor) ResponseStatusExceptionResolver(org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver) RequestMappingHandlerAdapter(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter) HandlerMethodReturnValueHandler(org.springframework.web.method.support.HandlerMethodReturnValueHandler) Mockito.mock(org.mockito.Mockito.mock) Ordered(org.springframework.core.Ordered) SimpleMappingExceptionResolver(org.springframework.web.servlet.handler.SimpleMappingExceptionResolver) Errors(org.springframework.validation.Errors) ResourceUrlProviderExposingInterceptor(org.springframework.web.servlet.resource.ResourceUrlProviderExposingInterceptor) ModelAttributeMethodProcessor(org.springframework.web.method.annotation.ModelAttributeMethodProcessor) InternalResourceViewResolver(org.springframework.web.servlet.view.InternalResourceViewResolver) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) Controller(org.springframework.stereotype.Controller) FileSystemResourceLoader(org.springframework.core.io.FileSystemResourceLoader) AbstractHandlerMapping(org.springframework.web.servlet.handler.AbstractHandlerMapping) RequestMappingInfo(org.springframework.web.servlet.mvc.method.RequestMappingInfo) MappingJackson2JsonView(org.springframework.web.servlet.view.json.MappingJackson2JsonView) GetMapping(org.springframework.web.bind.annotation.GetMapping) HandlerInterceptor(org.springframework.web.servlet.HandlerInterceptor) Nullable(org.springframework.lang.Nullable) MessageCodesResolver(org.springframework.validation.MessageCodesResolver) APPLICATION_JSON(org.springframework.http.MediaType.APPLICATION_JSON) BeanPropertyBindingResult(org.springframework.validation.BeanPropertyBindingResult) CallableProcessingInterceptor(org.springframework.web.context.request.async.CallableProcessingInterceptor) ViewResolver(org.springframework.web.servlet.ViewResolver) ViewResolverComposite(org.springframework.web.servlet.view.ViewResolverComposite) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) CorsConfiguration(org.springframework.web.cors.CorsConfiguration) ResourceHttpRequestHandler(org.springframework.web.servlet.resource.ResourceHttpRequestHandler) HttpStatus(org.springframework.http.HttpStatus) View(org.springframework.web.servlet.View) MappingJackson2HttpMessageConverter(org.springframework.http.converter.json.MappingJackson2HttpMessageConverter) UrlPathHelper(org.springframework.web.util.UrlPathHelper) ContentNegotiationManager(org.springframework.web.accept.ContentNegotiationManager) HandlerTypePredicate(org.springframework.web.method.HandlerTypePredicate) Collections(java.util.Collections) MockServletContext(org.springframework.web.testfixture.servlet.MockServletContext) HandlerExecutionChain(org.springframework.web.servlet.HandlerExecutionChain) HandlerInterceptor(org.springframework.web.servlet.HandlerInterceptor) RequestMappingInfo(org.springframework.web.servlet.mvc.method.RequestMappingInfo) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) RequestMappingHandlerMapping(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping) HandlerMethod(org.springframework.web.method.HandlerMethod) AbstractHandlerMapping(org.springframework.web.servlet.handler.AbstractHandlerMapping) Test(org.junit.jupiter.api.Test)

Example 7 with AbstractHandlerMapping

use of org.springframework.web.servlet.handler.AbstractHandlerMapping in project spring-framework by spring-projects.

the class MvcNamespaceTests method testCors.

@Test
public void testCors() {
    loadBeanDefinitions("mvc-config-cors.xml");
    String[] beanNames = appContext.getBeanNamesForType(AbstractHandlerMapping.class);
    assertThat(beanNames.length).isEqualTo(2);
    for (String beanName : beanNames) {
        AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping) appContext.getBean(beanName);
        assertThat(handlerMapping).isNotNull();
        DirectFieldAccessor accessor = new DirectFieldAccessor(handlerMapping);
        Map<String, CorsConfiguration> configs = ((UrlBasedCorsConfigurationSource) accessor.getPropertyValue("corsConfigurationSource")).getCorsConfigurations();
        assertThat(configs).isNotNull();
        assertThat(configs.size()).isEqualTo(2);
        CorsConfiguration config = configs.get("/api/**");
        assertThat(config).isNotNull();
        assertThat(config.getAllowedOrigins().toArray()).isEqualTo(new String[] { "https://domain1.com", "https://domain2.com" });
        assertThat(config.getAllowedOriginPatterns().toArray()).isEqualTo(new String[] { "http://*.domain.com" });
        assertThat(config.getAllowedMethods().toArray()).isEqualTo(new String[] { "GET", "PUT" });
        assertThat(config.getAllowedHeaders().toArray()).isEqualTo(new String[] { "header1", "header2", "header3" });
        assertThat(config.getExposedHeaders().toArray()).isEqualTo(new String[] { "header1", "header2" });
        assertThat(config.getAllowCredentials()).isFalse();
        assertThat(config.getMaxAge()).isEqualTo(Long.valueOf(123));
        config = configs.get("/resources/**");
        assertThat(config.getAllowedOrigins().toArray()).isEqualTo(new String[] { "https://domain1.com" });
        assertThat(config.getAllowedMethods().toArray()).isEqualTo(new String[] { "GET", "HEAD", "POST" });
        assertThat(config.getAllowedHeaders().toArray()).isEqualTo(new String[] { "*" });
        assertThat(config.getExposedHeaders()).isNull();
        assertThat(config.getAllowCredentials()).isNull();
        assertThat(config.getMaxAge()).isEqualTo(1800L);
    }
}
Also used : UrlBasedCorsConfigurationSource(org.springframework.web.cors.UrlBasedCorsConfigurationSource) CorsConfiguration(org.springframework.web.cors.CorsConfiguration) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) AbstractHandlerMapping(org.springframework.web.servlet.handler.AbstractHandlerMapping) Test(org.junit.jupiter.api.Test)

Example 8 with AbstractHandlerMapping

use of org.springframework.web.servlet.handler.AbstractHandlerMapping in project spring-framework by spring-projects.

the class MvcNamespaceTests method testCorsMinimal.

@Test
public void testCorsMinimal() throws Exception {
    loadBeanDefinitions("mvc-config-cors-minimal.xml");
    String[] beanNames = appContext.getBeanNamesForType(AbstractHandlerMapping.class);
    assertThat(beanNames.length).isEqualTo(2);
    for (String beanName : beanNames) {
        AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping) appContext.getBean(beanName);
        assertThat(handlerMapping).isNotNull();
        DirectFieldAccessor accessor = new DirectFieldAccessor(handlerMapping);
        Map<String, CorsConfiguration> configs = ((UrlBasedCorsConfigurationSource) accessor.getPropertyValue("corsConfigurationSource")).getCorsConfigurations();
        assertThat(configs).isNotNull();
        assertThat(configs.size()).isEqualTo(1);
        CorsConfiguration config = configs.get("/**");
        assertThat(config).isNotNull();
        assertThat(config.getAllowedOrigins().toArray()).isEqualTo(new String[] { "*" });
        assertThat(config.getAllowedMethods().toArray()).isEqualTo(new String[] { "GET", "HEAD", "POST" });
        assertThat(config.getAllowedHeaders().toArray()).isEqualTo(new String[] { "*" });
        assertThat(config.getExposedHeaders()).isNull();
        assertThat(config.getAllowCredentials()).isNull();
        assertThat(config.getMaxAge()).isEqualTo(Long.valueOf(1800));
    }
}
Also used : UrlBasedCorsConfigurationSource(org.springframework.web.cors.UrlBasedCorsConfigurationSource) CorsConfiguration(org.springframework.web.cors.CorsConfiguration) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) AbstractHandlerMapping(org.springframework.web.servlet.handler.AbstractHandlerMapping) Test(org.junit.jupiter.api.Test)

Example 9 with AbstractHandlerMapping

use of org.springframework.web.servlet.handler.AbstractHandlerMapping in project spring-framework by spring-projects.

the class DelegatingWebMvcConfigurationIntegrationTests method resourceHandlerMappingUsesMvcInfrastructureByDefault.

@Test
void resourceHandlerMappingUsesMvcInfrastructureByDefault() {
    load(context -> context.registerBean(ResourceHandlerConfiguration.class));
    AbstractHandlerMapping handlerMapping = this.context.getBean("resourceHandlerMapping", AbstractHandlerMapping.class);
    assertThat(handlerMapping.getPathMatcher()).isSameAs(this.context.getBean("mvcPathMatcher"));
    assertThat(handlerMapping.getUrlPathHelper()).isSameAs(this.context.getBean("mvcUrlPathHelper"));
}
Also used : AbstractHandlerMapping(org.springframework.web.servlet.handler.AbstractHandlerMapping) Test(org.junit.jupiter.api.Test)

Example 10 with AbstractHandlerMapping

use of org.springframework.web.servlet.handler.AbstractHandlerMapping in project spring-framework by spring-projects.

the class WebMvcConfigurationSupport method viewControllerHandlerMapping.

/**
	 * Return a handler mapping ordered at 1 to map URL paths directly to
	 * view names. To configure view controllers, override
	 * {@link #addViewControllers}.
	 */
@Bean
public HandlerMapping viewControllerHandlerMapping() {
    ViewControllerRegistry registry = new ViewControllerRegistry();
    registry.setApplicationContext(this.applicationContext);
    addViewControllers(registry);
    AbstractHandlerMapping handlerMapping = registry.getHandlerMapping();
    handlerMapping = (handlerMapping != null ? handlerMapping : new EmptyHandlerMapping());
    handlerMapping.setPathMatcher(mvcPathMatcher());
    handlerMapping.setUrlPathHelper(mvcUrlPathHelper());
    handlerMapping.setInterceptors(getInterceptors());
    handlerMapping.setCorsConfigurations(getCorsConfigurations());
    return handlerMapping;
}
Also used : AbstractHandlerMapping(org.springframework.web.servlet.handler.AbstractHandlerMapping) Bean(org.springframework.context.annotation.Bean)

Aggregations

AbstractHandlerMapping (org.springframework.web.servlet.handler.AbstractHandlerMapping)17 Test (org.junit.jupiter.api.Test)9 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)5 Mockito.mock (org.mockito.Mockito.mock)5 Bean (org.springframework.context.annotation.Bean)5 Consumer (java.util.function.Consumer)4 AfterEach (org.junit.jupiter.api.AfterEach)4 ConfigurableApplicationContext (org.springframework.context.ConfigurableApplicationContext)4 AnnotationConfigUtils (org.springframework.context.annotation.AnnotationConfigUtils)4 Configuration (org.springframework.context.annotation.Configuration)4 ConversionService (org.springframework.core.convert.ConversionService)4 PathMatcher (org.springframework.util.PathMatcher)4 Validator (org.springframework.validation.Validator)4 ContentNegotiationManager (org.springframework.web.accept.ContentNegotiationManager)4 GenericWebApplicationContext (org.springframework.web.context.support.GenericWebApplicationContext)4 RequestMappingHandlerAdapter (org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter)4 RequestMappingHandlerMapping (org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping)4 MockServletContext (org.springframework.web.testfixture.servlet.MockServletContext)4 UrlPathHelper (org.springframework.web.util.UrlPathHelper)4 Test (org.junit.Test)3