org.springframework.web.servlet.handler.AbstractHandlerMapping Java Examples

The following examples show how to use org.springframework.web.servlet.handler.AbstractHandlerMapping. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebMvcConfigurationSupport.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Return a handler mapping ordered at 1 to map URL paths directly to
 * view names. To configure view controllers, override
 * {@link #addViewControllers}.
 */
@Bean
@Nullable
public HandlerMapping viewControllerHandlerMapping(PathMatcher mvcPathMatcher,
		UrlPathHelper mvcUrlPathHelper,
		FormattingConversionService mvcConversionService,
		ResourceUrlProvider mvcResourceUrlProvider) {
	ViewControllerRegistry registry = new ViewControllerRegistry(this.applicationContext);
	addViewControllers(registry);

	AbstractHandlerMapping handlerMapping = registry.buildHandlerMapping();
	if (handlerMapping == null) {
		return null;
	}
	handlerMapping.setPathMatcher(mvcPathMatcher);
	handlerMapping.setUrlPathHelper(mvcUrlPathHelper);
	handlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
	handlerMapping.setCorsConfigurations(getCorsConfigurations());
	return handlerMapping;
}
 
Example #2
Source File: WebMvcStompEndpointRegistry.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Return a handler mapping with the mapped ViewControllers; or {@code null}
 * in case of no registrations.
 */
public AbstractHandlerMapping getHandlerMapping() {
	Map<String, Object> urlMap = new LinkedHashMap<String, Object>();
	for (WebMvcStompWebSocketEndpointRegistration registration : this.registrations) {
		MultiValueMap<HttpRequestHandler, String> mappings = registration.getMappings();
		for (HttpRequestHandler httpHandler : mappings.keySet()) {
			for (String pattern : mappings.get(httpHandler)) {
				urlMap.put(pattern, httpHandler);
			}
		}
	}
	WebSocketHandlerMapping hm = new WebSocketHandlerMapping();
	hm.setUrlMap(urlMap);
	hm.setOrder(this.order);
	if (this.urlPathHelper != null) {
		hm.setUrlPathHelper(this.urlPathHelper);
	}
	return hm;
}
 
Example #3
Source File: ServletWebSocketHandlerRegistry.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Return a {@link HandlerMapping} with mapped {@link HttpRequestHandler}s.
 */
public AbstractHandlerMapping getHandlerMapping() {
	Map<String, Object> urlMap = new LinkedHashMap<String, Object>();
	for (ServletWebSocketHandlerRegistration registration : this.registrations) {
		MultiValueMap<HttpRequestHandler, String> mappings = registration.getMappings();
		for (HttpRequestHandler httpHandler : mappings.keySet()) {
			for (String pattern : mappings.get(httpHandler)) {
				urlMap.put(pattern, httpHandler);
			}
		}
	}
	WebSocketHandlerMapping hm = new WebSocketHandlerMapping();
	hm.setUrlMap(urlMap);
	hm.setOrder(this.order);
	if (this.urlPathHelper != null) {
		hm.setUrlPathHelper(this.urlPathHelper);
	}
	return hm;
}
 
Example #4
Source File: MvcNamespaceTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testCorsMinimal() throws Exception {
	loadBeanDefinitions("mvc-config-cors-minimal.xml", 14);

	String[] beanNames = appContext.getBeanNamesForType(AbstractHandlerMapping.class);
	assertEquals(2, beanNames.length);
	for (String beanName : beanNames) {
		AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping)appContext.getBean(beanName);
		assertNotNull(handlerMapping);
		Map<String, CorsConfiguration> configs = handlerMapping.getCorsConfigurations();
		assertNotNull(configs);
		assertEquals(1, configs.size());
		CorsConfiguration config = configs.get("/**");
		assertNotNull(config);
		assertArrayEquals(new String[]{"*"}, config.getAllowedOrigins().toArray());
		assertArrayEquals(new String[]{"GET", "HEAD", "POST"}, config.getAllowedMethods().toArray());
		assertArrayEquals(new String[]{"*"}, config.getAllowedHeaders().toArray());
		assertNull(config.getExposedHeaders());
		assertTrue(config.getAllowCredentials());
		assertEquals(new Long(1600), config.getMaxAge());
	}
}
 
Example #5
Source File: WebMvcConfigurationSupport.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Return a handler mapping ordered at Integer.MAX_VALUE-1 with mapped
 * resource handlers. To configure resource handling, override
 * {@link #addResourceHandlers}.
 */
@Bean
public HandlerMapping resourceHandlerMapping() {
	ResourceHandlerRegistry registry = new ResourceHandlerRegistry(this.applicationContext, this.servletContext);
	addResourceHandlers(registry);

	AbstractHandlerMapping handlerMapping = registry.getHandlerMapping();
	if (handlerMapping != null) {
		handlerMapping.setPathMatcher(mvcPathMatcher());
		handlerMapping.setUrlPathHelper(mvcUrlPathHelper());
		handlerMapping.setInterceptors(new HandlerInterceptor[] {
				new ResourceUrlProviderExposingInterceptor(mvcResourceUrlProvider())});
		handlerMapping.setCorsConfigurations(getCorsConfigurations());
	}
	else {
		handlerMapping = new EmptyHandlerMapping();
	}
	return handlerMapping;
}
 
Example #6
Source File: WebMvcConfigurationSupport.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Return a handler mapping ordered at Integer.MAX_VALUE-1 with mapped
 * resource handlers. To configure resource handling, override
 * {@link #addResourceHandlers}.
 */
@Bean
public HandlerMapping resourceHandlerMapping() {
	ResourceHandlerRegistry registry = new ResourceHandlerRegistry(this.applicationContext,
			this.servletContext, mvcContentNegotiationManager());
	addResourceHandlers(registry);

	AbstractHandlerMapping handlerMapping = registry.getHandlerMapping();
	if (handlerMapping != null) {
		handlerMapping.setPathMatcher(mvcPathMatcher());
		handlerMapping.setUrlPathHelper(mvcUrlPathHelper());
		handlerMapping.setInterceptors(new ResourceUrlProviderExposingInterceptor(mvcResourceUrlProvider()));
		handlerMapping.setCorsConfigurations(getCorsConfigurations());
	}
	else {
		handlerMapping = new EmptyHandlerMapping();
	}
	return handlerMapping;
}
 
Example #7
Source File: WebMvcStompEndpointRegistry.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Return a handler mapping with the mapped ViewControllers.
 */
public AbstractHandlerMapping getHandlerMapping() {
	Map<String, Object> urlMap = new LinkedHashMap<>();
	for (WebMvcStompWebSocketEndpointRegistration registration : this.registrations) {
		MultiValueMap<HttpRequestHandler, String> mappings = registration.getMappings();
		mappings.forEach((httpHandler, patterns) -> {
			for (String pattern : patterns) {
				urlMap.put(pattern, httpHandler);
			}
		});
	}
	WebSocketHandlerMapping hm = new WebSocketHandlerMapping();
	hm.setUrlMap(urlMap);
	hm.setOrder(this.order);
	if (this.urlPathHelper != null) {
		hm.setUrlPathHelper(this.urlPathHelper);
	}
	return hm;
}
 
Example #8
Source File: ServletWebSocketHandlerRegistry.java    From java-technology-stack with MIT License 6 votes vote down vote up
public AbstractHandlerMapping getHandlerMapping() {
	Map<String, Object> urlMap = new LinkedHashMap<>();
	for (ServletWebSocketHandlerRegistration registration : this.registrations) {
		MultiValueMap<HttpRequestHandler, String> mappings = registration.getMappings();
		mappings.forEach((httpHandler, patterns) -> {
			for (String pattern : patterns) {
				urlMap.put(pattern, httpHandler);
			}
		});
	}
	WebSocketHandlerMapping hm = new WebSocketHandlerMapping();
	hm.setUrlMap(urlMap);
	hm.setOrder(this.order);
	if (this.urlPathHelper != null) {
		hm.setUrlPathHelper(this.urlPathHelper);
	}
	return hm;
}
 
Example #9
Source File: MvcNamespaceTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testCorsMinimal() throws Exception {
	loadBeanDefinitions("mvc-config-cors-minimal.xml");

	String[] beanNames = appContext.getBeanNamesForType(AbstractHandlerMapping.class);
	assertEquals(2, beanNames.length);
	for (String beanName : beanNames) {
		AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping)appContext.getBean(beanName);
		assertNotNull(handlerMapping);
		DirectFieldAccessor accessor = new DirectFieldAccessor(handlerMapping);
		Map<String, CorsConfiguration> configs = ((UrlBasedCorsConfigurationSource)accessor
				.getPropertyValue("corsConfigurationSource")).getCorsConfigurations();
		assertNotNull(configs);
		assertEquals(1, configs.size());
		CorsConfiguration config = configs.get("/**");
		assertNotNull(config);
		assertArrayEquals(new String[]{"*"}, config.getAllowedOrigins().toArray());
		assertArrayEquals(new String[]{"GET", "HEAD", "POST"}, config.getAllowedMethods().toArray());
		assertArrayEquals(new String[]{"*"}, config.getAllowedHeaders().toArray());
		assertNull(config.getExposedHeaders());
		assertNull(config.getAllowCredentials());
		assertEquals(Long.valueOf(1800), config.getMaxAge());
	}
}
 
Example #10
Source File: WebMvcConfigurationSupport.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Return a handler mapping ordered at Integer.MAX_VALUE-1 with mapped
 * resource handlers. To configure resource handling, override
 * {@link #addResourceHandlers}.
 */
@Bean
@Nullable
public HandlerMapping resourceHandlerMapping() {
	Assert.state(this.applicationContext != null, "No ApplicationContext set");
	Assert.state(this.servletContext != null, "No ServletContext set");

	ResourceHandlerRegistry registry = new ResourceHandlerRegistry(this.applicationContext,
			this.servletContext, mvcContentNegotiationManager(), mvcUrlPathHelper());
	addResourceHandlers(registry);

	AbstractHandlerMapping handlerMapping = registry.getHandlerMapping();
	if (handlerMapping == null) {
		return null;
	}
	handlerMapping.setPathMatcher(mvcPathMatcher());
	handlerMapping.setUrlPathHelper(mvcUrlPathHelper());
	handlerMapping.setInterceptors(getInterceptors());
	handlerMapping.setCorsConfigurations(getCorsConfigurations());
	return handlerMapping;
}
 
Example #11
Source File: WebMvcConfigurationSupport.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Return a handler mapping ordered at 1 to map URL paths directly to
 * view names. To configure view controllers, override
 * {@link #addViewControllers}.
 */
@Bean
@Nullable
public HandlerMapping viewControllerHandlerMapping() {
	ViewControllerRegistry registry = new ViewControllerRegistry(this.applicationContext);
	addViewControllers(registry);

	AbstractHandlerMapping handlerMapping = registry.buildHandlerMapping();
	if (handlerMapping == null) {
		return null;
	}
	handlerMapping.setPathMatcher(mvcPathMatcher());
	handlerMapping.setUrlPathHelper(mvcUrlPathHelper());
	handlerMapping.setInterceptors(getInterceptors());
	handlerMapping.setCorsConfigurations(getCorsConfigurations());
	return handlerMapping;
}
 
Example #12
Source File: SpringMvcPolyfill.java    From Milkomeda with MIT License 6 votes vote down vote up
/**
 * 查找adaptedInterceptors
 * @param handlerMapping        AbstractHandlerMapping实现类
 * @throws NoSuchFieldException 反射字段异常
 */
private static void findAdaptedInterceptorsField(AbstractHandlerMapping handlerMapping) throws NoSuchFieldException {
    if (adaptedInterceptorsField == null) {
        // 虽然用了反射,但这些代码在只在启动时加载
        // 查找继承链
        // RequestMappingHandlerMapping -> RequestMappingInfoHandlerMapping -> AbstractHandlerMethodMapping -> AbstractHandlerMapping
        // WelcomePageHandlerMapping -> AbstractUrlHandlerMapping -> AbstractHandlerMapping
        Class<?> abstractHandlerMapping = handlerMapping.getClass();
        while (abstractHandlerMapping != AbstractHandlerMapping.class) {
            abstractHandlerMapping = abstractHandlerMapping.getSuperclass();
        }
        // TODO <mark> 由于使用底层API, 这个AbstractHandlerMapping.adaptedInterceptors很后的版本可能会改
        adaptedInterceptorsField = abstractHandlerMapping.getDeclaredField("adaptedInterceptors");
        adaptedInterceptorsField.setAccessible(true);
    }
}
 
Example #13
Source File: SpringMvcPolyfill.java    From Milkomeda with MIT License 6 votes vote down vote up
/**
 * 动态删除拦截器
 * @param interceptor       HandlerInterceptor
 * @param handlerMapping    AbstractHandlerMapping实现类
 */
@SuppressWarnings("all")
public static void removeDynamicInterceptor(HandlerInterceptor interceptor, AbstractHandlerMapping handlerMapping) {
    if (interceptor == null) return;
    try {
        findAdaptedInterceptorsField(handlerMapping);
        List<HandlerInterceptor> handlerInterceptors = (List<HandlerInterceptor>) adaptedInterceptorsField.get(handlerMapping);
        List<HandlerInterceptor> shouldRemoveInterceptors = handlerInterceptors.stream().filter(itor -> {
            // 只判断映射的拦截器类型
            if (itor instanceof HydrogenMappedInterceptor) {
                return itor.equals(interceptor);
            }
            return false;
        }).collect(Collectors.toList());
        handlerInterceptors.removeAll(shouldRemoveInterceptors);
        adaptedInterceptorsField.set(handlerMapping, handlerInterceptors);
    } catch (Exception e) {
        log.error("SpringMvcPolyfill invoke AbstractHandlerMapping.adaptedInterceptors error with msg: {}",  e.getMessage(), e);
    }
}
 
Example #14
Source File: WebMvcConfigurationSupport.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Return a handler mapping ordered at Integer.MAX_VALUE-1 with mapped
 * resource handlers. To configure resource handling, override
 * {@link #addResourceHandlers}.
 */
@Bean
@Nullable
public HandlerMapping resourceHandlerMapping(UrlPathHelper mvcUrlPathHelper,
		PathMatcher mvcPathMatcher,
		ContentNegotiationManager mvcContentNegotiationManager,
		FormattingConversionService mvcConversionService,
		ResourceUrlProvider mvcResourceUrlProvider) {
	Assert.state(this.applicationContext != null, "No ApplicationContext set");
	Assert.state(this.servletContext != null, "No ServletContext set");

	ResourceHandlerRegistry registry = new ResourceHandlerRegistry(this.applicationContext,
			this.servletContext, mvcContentNegotiationManager, mvcUrlPathHelper);
	addResourceHandlers(registry);

	AbstractHandlerMapping handlerMapping = registry.getHandlerMapping();
	if (handlerMapping == null) {
		return null;
	}
	handlerMapping.setPathMatcher(mvcPathMatcher);
	handlerMapping.setUrlPathHelper(mvcUrlPathHelper);
	handlerMapping.setInterceptors(getInterceptors(mvcConversionService, mvcResourceUrlProvider));
	handlerMapping.setCorsConfigurations(getCorsConfigurations());
	return handlerMapping;
}
 
Example #15
Source File: WebMvcStompEndpointRegistry.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Return a handler mapping with the mapped ViewControllers.
 */
public AbstractHandlerMapping getHandlerMapping() {
	Map<String, Object> urlMap = new LinkedHashMap<>();
	for (WebMvcStompWebSocketEndpointRegistration registration : this.registrations) {
		MultiValueMap<HttpRequestHandler, String> mappings = registration.getMappings();
		mappings.forEach((httpHandler, patterns) -> {
			for (String pattern : patterns) {
				urlMap.put(pattern, httpHandler);
			}
		});
	}
	WebSocketHandlerMapping hm = new WebSocketHandlerMapping();
	hm.setUrlMap(urlMap);
	hm.setOrder(this.order);
	if (this.urlPathHelper != null) {
		hm.setUrlPathHelper(this.urlPathHelper);
	}
	return hm;
}
 
Example #16
Source File: ServletWebSocketHandlerRegistry.java    From spring-analysis-note with MIT License 6 votes vote down vote up
public AbstractHandlerMapping getHandlerMapping() {
	Map<String, Object> urlMap = new LinkedHashMap<>();
	for (ServletWebSocketHandlerRegistration registration : this.registrations) {
		MultiValueMap<HttpRequestHandler, String> mappings = registration.getMappings();
		mappings.forEach((httpHandler, patterns) -> {
			for (String pattern : patterns) {
				urlMap.put(pattern, httpHandler);
			}
		});
	}
	WebSocketHandlerMapping hm = new WebSocketHandlerMapping();
	hm.setUrlMap(urlMap);
	hm.setOrder(this.order);
	if (this.urlPathHelper != null) {
		hm.setUrlPathHelper(this.urlPathHelper);
	}
	return hm;
}
 
Example #17
Source File: MvcNamespaceTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testCorsMinimal() throws Exception {
	loadBeanDefinitions("mvc-config-cors-minimal.xml");

	String[] beanNames = appContext.getBeanNamesForType(AbstractHandlerMapping.class);
	assertEquals(2, beanNames.length);
	for (String beanName : beanNames) {
		AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping)appContext.getBean(beanName);
		assertNotNull(handlerMapping);
		DirectFieldAccessor accessor = new DirectFieldAccessor(handlerMapping);
		Map<String, CorsConfiguration> configs = ((UrlBasedCorsConfigurationSource) accessor
				.getPropertyValue("corsConfigurationSource")).getCorsConfigurations();
		assertNotNull(configs);
		assertEquals(1, configs.size());
		CorsConfiguration config = configs.get("/**");
		assertNotNull(config);
		assertArrayEquals(new String[]{"*"}, config.getAllowedOrigins().toArray());
		assertArrayEquals(new String[]{"GET", "HEAD", "POST"}, config.getAllowedMethods().toArray());
		assertArrayEquals(new String[]{"*"}, config.getAllowedHeaders().toArray());
		assertNull(config.getExposedHeaders());
		assertNull(config.getAllowCredentials());
		assertEquals(Long.valueOf(1800), config.getMaxAge());
	}
}
 
Example #18
Source File: ResourceHandlerRegistry.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Return a handler mapping with the mapped resource handlers; or {@code null} in case
 * of no registrations.
 */
@Nullable
protected AbstractHandlerMapping getHandlerMapping() {
	if (this.registrations.isEmpty()) {
		return null;
	}

	Map<String, HttpRequestHandler> urlMap = new LinkedHashMap<>();
	for (ResourceHandlerRegistration registration : this.registrations) {
		for (String pathPattern : registration.getPathPatterns()) {
			ResourceHttpRequestHandler handler = registration.getRequestHandler();
			if (this.pathHelper != null) {
				handler.setUrlPathHelper(this.pathHelper);
			}
			if (this.contentNegotiationManager != null) {
				handler.setContentNegotiationManager(this.contentNegotiationManager);
			}
			handler.setServletContext(this.servletContext);
			handler.setApplicationContext(this.applicationContext);
			try {
				handler.afterPropertiesSet();
			}
			catch (Throwable ex) {
				throw new BeanInitializationException("Failed to init ResourceHttpRequestHandler", ex);
			}
			urlMap.put(pathPattern, handler);
		}
	}

	SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
	handlerMapping.setOrder(this.order);
	handlerMapping.setUrlMap(urlMap);
	return handlerMapping;
}
 
Example #19
Source File: ResourceHandlerRegistry.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Return a handler mapping with the mapped resource handlers; or {@code null} in case
 * of no registrations.
 */
@Nullable
protected AbstractHandlerMapping getHandlerMapping() {
	if (this.registrations.isEmpty()) {
		return null;
	}

	Map<String, HttpRequestHandler> urlMap = new LinkedHashMap<>();
	for (ResourceHandlerRegistration registration : this.registrations) {
		for (String pathPattern : registration.getPathPatterns()) {
			ResourceHttpRequestHandler handler = registration.getRequestHandler();
			if (this.pathHelper != null) {
				handler.setUrlPathHelper(this.pathHelper);
			}
			if (this.contentNegotiationManager != null) {
				handler.setContentNegotiationManager(this.contentNegotiationManager);
			}
			handler.setServletContext(this.servletContext);
			handler.setApplicationContext(this.applicationContext);
			try {
				handler.afterPropertiesSet();
			}
			catch (Throwable ex) {
				throw new BeanInitializationException("Failed to init ResourceHttpRequestHandler", ex);
			}
			urlMap.put(pathPattern, handler);
		}
	}

	SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
	handlerMapping.setOrder(this.order);
	handlerMapping.setUrlMap(urlMap);
	return handlerMapping;
}
 
Example #20
Source File: WebMvcConfigurationSupportTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void emptyDefaultServletHandlerMapping() {
	ApplicationContext context = initContext(WebConfig.class);
	String name = "defaultServletHandlerMapping";
	AbstractHandlerMapping handlerMapping = context.getBean(name, AbstractHandlerMapping.class);

	assertNotNull(handlerMapping);
	assertEquals(Integer.MAX_VALUE, handlerMapping.getOrder());
	assertTrue(handlerMapping.getClass().getName().endsWith("EmptyHandlerMapping"));
}
 
Example #21
Source File: WebMvcConfigurationSupportTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void emptyResourceHandlerMapping() {
	ApplicationContext context = initContext(WebConfig.class);
	AbstractHandlerMapping handlerMapping = context.getBean("resourceHandlerMapping", AbstractHandlerMapping.class);

	assertNotNull(handlerMapping);
	assertEquals(Integer.MAX_VALUE, handlerMapping.getOrder());
	assertTrue(handlerMapping.getClass().getName().endsWith("EmptyHandlerMapping"));
}
 
Example #22
Source File: WebMvcConfigurationSupportTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void emptyViewControllerHandlerMapping() {
	ApplicationContext context = initContext(WebConfig.class);
	String name = "viewControllerHandlerMapping";
	AbstractHandlerMapping handlerMapping = context.getBean(name, AbstractHandlerMapping.class);

	assertNotNull(handlerMapping);
	assertEquals(Integer.MAX_VALUE, handlerMapping.getOrder());
	assertTrue(handlerMapping.getClass().getName().endsWith("EmptyHandlerMapping"));
}
 
Example #23
Source File: MvcNamespaceTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testCors() throws Exception {
	loadBeanDefinitions("mvc-config-cors.xml", 14);

	String[] beanNames = appContext.getBeanNamesForType(AbstractHandlerMapping.class);
	assertEquals(2, beanNames.length);
	for (String beanName : beanNames) {
		AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping)appContext.getBean(beanName);
		assertNotNull(handlerMapping);
		Map<String, CorsConfiguration> configs = handlerMapping.getCorsConfigurations();
		assertNotNull(configs);
		assertEquals(2, configs.size());
		CorsConfiguration config = configs.get("/api/**");
		assertNotNull(config);
		assertArrayEquals(new String[]{"http://domain1.com", "http://domain2.com"}, config.getAllowedOrigins().toArray());
		assertArrayEquals(new String[]{"GET", "PUT"}, config.getAllowedMethods().toArray());
		assertArrayEquals(new String[]{"header1", "header2", "header3"}, config.getAllowedHeaders().toArray());
		assertArrayEquals(new String[]{"header1", "header2"}, config.getExposedHeaders().toArray());
		assertFalse(config.getAllowCredentials());
		assertEquals(new Long(123), config.getMaxAge());
		config = configs.get("/resources/**");
		assertArrayEquals(new String[]{"http://domain1.com"}, config.getAllowedOrigins().toArray());
		assertArrayEquals(new String[]{"GET", "HEAD", "POST"}, config.getAllowedMethods().toArray());
		assertArrayEquals(new String[]{"*"}, config.getAllowedHeaders().toArray());
		assertNull(config.getExposedHeaders());
		assertTrue(config.getAllowCredentials());
		assertEquals(new Long(1600), config.getMaxAge());
	}
}
 
Example #24
Source File: WebMvcConfigurationSupport.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Return a handler mapping ordered at Integer.MAX_VALUE with a mapped
 * default servlet handler. To configure "default" Servlet handling,
 * override {@link #configureDefaultServletHandling}.
 */
@Bean
public HandlerMapping defaultServletHandlerMapping() {
	DefaultServletHandlerConfigurer configurer = new DefaultServletHandlerConfigurer(servletContext);
	configureDefaultServletHandling(configurer);
	AbstractHandlerMapping handlerMapping = configurer.getHandlerMapping();
	handlerMapping = handlerMapping != null ? handlerMapping : new EmptyHandlerMapping();
	return handlerMapping;
}
 
Example #25
Source File: MvcNamespaceTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testCors() throws Exception {
	loadBeanDefinitions("mvc-config-cors.xml");

	String[] beanNames = appContext.getBeanNamesForType(AbstractHandlerMapping.class);
	assertEquals(2, beanNames.length);
	for (String beanName : beanNames) {
		AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping)appContext.getBean(beanName);
		assertNotNull(handlerMapping);
		DirectFieldAccessor accessor = new DirectFieldAccessor(handlerMapping);
		Map<String, CorsConfiguration> configs = ((UrlBasedCorsConfigurationSource) accessor
				.getPropertyValue("corsConfigurationSource")).getCorsConfigurations();
		assertNotNull(configs);
		assertEquals(2, configs.size());
		CorsConfiguration config = configs.get("/api/**");
		assertNotNull(config);
		assertArrayEquals(new String[]{"https://domain1.com", "https://domain2.com"}, config.getAllowedOrigins().toArray());
		assertArrayEquals(new String[]{"GET", "PUT"}, config.getAllowedMethods().toArray());
		assertArrayEquals(new String[]{"header1", "header2", "header3"}, config.getAllowedHeaders().toArray());
		assertArrayEquals(new String[]{"header1", "header2"}, config.getExposedHeaders().toArray());
		assertFalse(config.getAllowCredentials());
		assertEquals(Long.valueOf(123), config.getMaxAge());
		config = configs.get("/resources/**");
		assertArrayEquals(new String[]{"https://domain1.com"}, config.getAllowedOrigins().toArray());
		assertArrayEquals(new String[]{"GET", "HEAD", "POST"}, config.getAllowedMethods().toArray());
		assertArrayEquals(new String[]{"*"}, config.getAllowedHeaders().toArray());
		assertNull(config.getExposedHeaders());
		assertNull(config.getAllowCredentials());
		assertEquals(Long.valueOf(1800), config.getMaxAge());
	}
}
 
Example #26
Source File: WebMvcConfigurationSupport.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #27
Source File: ResourceHandlerRegistry.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Return a handler mapping with the mapped resource handlers; or {@code null} in case of no registrations.
 */
protected AbstractHandlerMapping getHandlerMapping() {
	if (registrations.isEmpty()) {
		return null;
	}

	Map<String, HttpRequestHandler> urlMap = new LinkedHashMap<String, HttpRequestHandler>();
	for (ResourceHandlerRegistration registration : this.registrations) {
		for (String pathPattern : registration.getPathPatterns()) {
			ResourceHttpRequestHandler handler = registration.getRequestHandler();
			handler.setServletContext(this.servletContext);
			handler.setApplicationContext(this.appContext);
			try {
				handler.afterPropertiesSet();
			}
			catch (Exception e) {
				throw new BeanInitializationException("Failed to init ResourceHttpRequestHandler", e);
			}
			urlMap.put(pathPattern, handler);
		}
	}

	SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
	handlerMapping.setOrder(order);
	handlerMapping.setUrlMap(urlMap);
	return handlerMapping;
}
 
Example #28
Source File: DefaultServletHandlerConfigurer.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Return a handler mapping instance ordered at {@link Integer#MAX_VALUE} containing the
 * {@link DefaultServletHttpRequestHandler} instance mapped to {@code "/**"}; or {@code null} if
 * default servlet handling was not been enabled.
 */
protected AbstractHandlerMapping getHandlerMapping() {
	if (handler == null) {
		return null;
	}

	Map<String, HttpRequestHandler> urlMap = new HashMap<String, HttpRequestHandler>();
	urlMap.put("/**", handler);

	SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
	handlerMapping.setOrder(Integer.MAX_VALUE);
	handlerMapping.setUrlMap(urlMap);
	return handlerMapping;
}
 
Example #29
Source File: WebMvcConfigurationSupport.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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(this.applicationContext);
	addViewControllers(registry);

	AbstractHandlerMapping handlerMapping = registry.buildHandlerMapping();
	handlerMapping = (handlerMapping != null ? handlerMapping : new EmptyHandlerMapping());
	handlerMapping.setPathMatcher(mvcPathMatcher());
	handlerMapping.setUrlPathHelper(mvcUrlPathHelper());
	handlerMapping.setInterceptors(getInterceptors());
	handlerMapping.setCorsConfigurations(getCorsConfigurations());
	return handlerMapping;
}
 
Example #30
Source File: ResourceHandlerRegistry.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return a handler mapping with the mapped resource handlers; or {@code null} in case
 * of no registrations.
 */
protected AbstractHandlerMapping getHandlerMapping() {
	if (this.registrations.isEmpty()) {
		return null;
	}

	Map<String, HttpRequestHandler> urlMap = new LinkedHashMap<String, HttpRequestHandler>();
	for (ResourceHandlerRegistration registration : this.registrations) {
		for (String pathPattern : registration.getPathPatterns()) {
			ResourceHttpRequestHandler handler = registration.getRequestHandler();
			handler.setServletContext(this.servletContext);
			handler.setApplicationContext(this.applicationContext);
			handler.setContentNegotiationManager(this.contentNegotiationManager);
			try {
				handler.afterPropertiesSet();
			}
			catch (Throwable ex) {
				throw new BeanInitializationException("Failed to init ResourceHttpRequestHandler", ex);
			}
			urlMap.put(pathPattern, handler);
		}
	}

	SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
	handlerMapping.setOrder(order);
	handlerMapping.setUrlMap(urlMap);
	return handlerMapping;
}