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

The following examples show how to use org.springframework.web.servlet.handler.AbstractHandlerMapping. These examples are extracted from open source projects. 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 Project: spring-analysis-note   Source File: WebMvcConfigurationSupport.java    License: 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 Project: spring-analysis-note   Source File: WebMvcConfigurationSupport.java    License: 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 3
Source Project: spring-analysis-note   Source File: MvcNamespaceTests.java    License: 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 4
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 5
Source Project: spring-analysis-note   Source File: WebMvcStompEndpointRegistry.java    License: 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 6
Source Project: Milkomeda   Source File: SpringMvcPolyfill.java    License: 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 7
Source Project: Milkomeda   Source File: SpringMvcPolyfill.java    License: 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 8
Source Project: java-technology-stack   Source File: WebMvcConfigurationSupport.java    License: 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 9
Source Project: java-technology-stack   Source File: WebMvcConfigurationSupport.java    License: 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 10
Source Project: java-technology-stack   Source File: MvcNamespaceTests.java    License: 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 11
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 12
/**
 * 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 13
/**
 * 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 14
/**
 * 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 15
Source Project: spring4-understanding   Source File: MvcNamespaceTests.java    License: 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 16
/**
 * 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 17
/**
 * 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 18
Source Project: spring-analysis-note   Source File: ResourceHandlerRegistry.java    License: 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 Project: spring-analysis-note   Source File: MvcNamespaceTests.java    License: 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 20
Source Project: Milkomeda   Source File: SpringMvcPolyfill.java    License: MIT License 5 votes vote down vote up
/**
 * 动态添加拦截器
 * @param interceptor       拦截器
 * @param order             排序
 * @param includeURLs       需要拦截的URL
 * @param excludeURLs       排除拦截的URL
 * @param handlerMapping    AbstractHandlerMapping实现类
 */
@SuppressWarnings("all")
public static void addDynamicInterceptor(HandlerInterceptor interceptor, int order, List<String> includeURLs, List<String> excludeURLs, AbstractHandlerMapping handlerMapping) {
    String[] include = StringUtils.toStringArray(includeURLs);
    String[] exclude = StringUtils.toStringArray(excludeURLs);
    // HandlerInterceptor -> MappedInterceptor -> HydrogenMappedInterceptor
    HydrogenMappedInterceptor hmi = new HydrogenMappedInterceptor(new MappedInterceptor(include, exclude, interceptor));
    // 内部的处理流程会设置,然而不是最终采纳的拦截器列表
    // handlerMapping.setInterceptors(mappedInterceptor);
    hmi.setOrder(order);
    try {
        findAdaptedInterceptorsField(handlerMapping);
        // 添加到可采纳的拦截器列表,让拦截器处理器Chain流程获取得到这个拦截器
        List<HandlerInterceptor> handlerInterceptors = (List<HandlerInterceptor>) adaptedInterceptorsField.get(handlerMapping);
        // 过滤添加过的拦截器
        boolean mapped = handlerInterceptors.stream().anyMatch(itor -> {
            // 只判断HydrogenMappedInterceptor拦截器类型
            if (itor instanceof HydrogenMappedInterceptor) {
                return itor.equals(hmi);
            }
            return false;
        });
        if (mapped) {
            return;
        }
        handlerInterceptors.add(hmi);
        // 仿Spring MVC源码对拦截器排序
        handlerInterceptors = handlerInterceptors.stream()
                .sorted(OrderComparator.INSTANCE.withSourceProvider(itor -> {
                    if (itor instanceof HydrogenMappedInterceptor) {
                        return (Ordered) ((HydrogenMappedInterceptor) itor)::getOrder;
                    }
                    return null;
                })).collect(Collectors.toList());
        adaptedInterceptorsField.set(handlerMapping, handlerInterceptors);
    } catch (Exception e) {
        log.error("SpringMvcPolyfill invoke AbstractHandlerMapping.adaptedInterceptors error with msg: {}",  e.getMessage(), e);
    }
}
 
Example 21
Source Project: java-technology-stack   Source File: ResourceHandlerRegistry.java    License: 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 22
Source Project: java-technology-stack   Source File: MvcNamespaceTests.java    License: 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[]{"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(Long.valueOf(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());
		assertNull(config.getAllowCredentials());
		assertEquals(Long.valueOf(1800), config.getMaxAge());
	}
}
 
Example 23
Source Project: lams   Source File: ResourceHandlerRegistry.java    License: 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;
}
 
Example 24
/**
 * 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 25
/**
 * 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 26
/**
 * 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 27
/**
 * 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 28
/**
 * 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 29
Source Project: spring4-understanding   Source File: MvcNamespaceTests.java    License: 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 30
@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"));
}