Search in sources :

Example 1 with ResourceHttpRequestHandler

use of org.springframework.web.servlet.resource.ResourceHttpRequestHandler in project spring-boot by spring-projects.

the class WebMvcAutoConfigurationTests method getMappingLocations.

@SuppressWarnings("unchecked")
protected Map<String, List<Resource>> getMappingLocations(HandlerMapping mapping) throws IllegalAccessException {
    Map<String, List<Resource>> mappingLocations = new LinkedHashMap<>();
    if (mapping instanceof SimpleUrlHandlerMapping) {
        Field locationsField = ReflectionUtils.findField(ResourceHttpRequestHandler.class, "locations");
        locationsField.setAccessible(true);
        for (Map.Entry<String, Object> entry : ((SimpleUrlHandlerMapping) mapping).getHandlerMap().entrySet()) {
            ResourceHttpRequestHandler handler = (ResourceHttpRequestHandler) entry.getValue();
            mappingLocations.put(entry.getKey(), (List<Resource>) locationsField.get(handler));
        }
    }
    return mappingLocations;
}
Also used : Field(java.lang.reflect.Field) ResourceHttpRequestHandler(org.springframework.web.servlet.resource.ResourceHttpRequestHandler) Resource(org.springframework.core.io.Resource) ClassPathResource(org.springframework.core.io.ClassPathResource) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) SimpleUrlHandlerMapping(org.springframework.web.servlet.handler.SimpleUrlHandlerMapping) LinkedHashMap(java.util.LinkedHashMap)

Example 2 with ResourceHttpRequestHandler

use of org.springframework.web.servlet.resource.ResourceHttpRequestHandler in project spring-framework by spring-projects.

the class ResourceHandlerRegistration method getRequestHandler.

/**
	 * Returns a {@link ResourceHttpRequestHandler} instance.
	 */
protected ResourceHttpRequestHandler getRequestHandler() {
    ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler();
    if (this.resourceChainRegistration != null) {
        handler.setResourceResolvers(this.resourceChainRegistration.getResourceResolvers());
        handler.setResourceTransformers(this.resourceChainRegistration.getResourceTransformers());
    }
    handler.setLocations(this.locations);
    if (this.cacheControl != null) {
        handler.setCacheControl(this.cacheControl);
    } else if (this.cachePeriod != null) {
        handler.setCacheSeconds(this.cachePeriod);
    }
    return handler;
}
Also used : ResourceHttpRequestHandler(org.springframework.web.servlet.resource.ResourceHttpRequestHandler)

Example 3 with ResourceHttpRequestHandler

use of org.springframework.web.servlet.resource.ResourceHttpRequestHandler in project spring-framework by spring-projects.

the class ResourceHandlerRegistry method getHandlerMapping.

/**
	 * 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<>();
    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;
}
Also used : BeanInitializationException(org.springframework.beans.factory.BeanInitializationException) ResourceHttpRequestHandler(org.springframework.web.servlet.resource.ResourceHttpRequestHandler) ResourceHttpRequestHandler(org.springframework.web.servlet.resource.ResourceHttpRequestHandler) HttpRequestHandler(org.springframework.web.HttpRequestHandler) SimpleUrlHandlerMapping(org.springframework.web.servlet.handler.SimpleUrlHandlerMapping) LinkedHashMap(java.util.LinkedHashMap)

Example 4 with ResourceHttpRequestHandler

use of org.springframework.web.servlet.resource.ResourceHttpRequestHandler in project spring-framework by spring-projects.

the class WebMvcConfigurationSupportExtensionTests method contentNegotiation.

@Test
public void contentNegotiation() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo.json");
    NativeWebRequest webRequest = new ServletWebRequest(request);
    RequestMappingHandlerMapping mapping = this.config.requestMappingHandlerMapping();
    ContentNegotiationManager manager = mapping.getContentNegotiationManager();
    assertEquals(Collections.singletonList(APPLICATION_JSON), manager.resolveMediaTypes(webRequest));
    request.setRequestURI("/foo.xml");
    assertEquals(Collections.singletonList(APPLICATION_XML), manager.resolveMediaTypes(webRequest));
    request.setRequestURI("/foo.rss");
    assertEquals(Collections.singletonList(MediaType.valueOf("application/rss+xml")), manager.resolveMediaTypes(webRequest));
    request.setRequestURI("/foo.atom");
    assertEquals(Collections.singletonList(APPLICATION_ATOM_XML), manager.resolveMediaTypes(webRequest));
    request.setRequestURI("/foo");
    request.setParameter("f", "json");
    assertEquals(Collections.singletonList(APPLICATION_JSON), manager.resolveMediaTypes(webRequest));
    request.setRequestURI("/resources/foo.gif");
    SimpleUrlHandlerMapping handlerMapping = (SimpleUrlHandlerMapping) this.config.resourceHandlerMapping();
    handlerMapping.setApplicationContext(this.context);
    HandlerExecutionChain chain = handlerMapping.getHandler(request);
    assertNotNull(chain);
    ResourceHttpRequestHandler handler = (ResourceHttpRequestHandler) chain.getHandler();
    assertNotNull(handler);
    assertSame(manager, handler.getContentNegotiationManager());
}
Also used : ResourceHttpRequestHandler(org.springframework.web.servlet.resource.ResourceHttpRequestHandler) ContentNegotiationManager(org.springframework.web.accept.ContentNegotiationManager) HandlerExecutionChain(org.springframework.web.servlet.HandlerExecutionChain) MockHttpServletRequest(org.springframework.mock.web.test.MockHttpServletRequest) RequestMappingHandlerMapping(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping) NativeWebRequest(org.springframework.web.context.request.NativeWebRequest) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) SimpleUrlHandlerMapping(org.springframework.web.servlet.handler.SimpleUrlHandlerMapping) Test(org.junit.Test)

Example 5 with ResourceHttpRequestHandler

use of org.springframework.web.servlet.resource.ResourceHttpRequestHandler in project spring-framework by spring-projects.

the class MvcNamespaceTests method testResources.

@Test
public void testResources() throws Exception {
    loadBeanDefinitions("mvc-config-resources.xml", 20);
    HttpRequestHandlerAdapter adapter = appContext.getBean(HttpRequestHandlerAdapter.class);
    assertNotNull(adapter);
    RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class);
    ContentNegotiationManager manager = mapping.getContentNegotiationManager();
    ResourceHttpRequestHandler handler = appContext.getBean(ResourceHttpRequestHandler.class);
    assertNotNull(handler);
    assertSame(manager, handler.getContentNegotiationManager());
    SimpleUrlHandlerMapping resourceMapping = appContext.getBean(SimpleUrlHandlerMapping.class);
    assertNotNull(resourceMapping);
    assertEquals(Ordered.LOWEST_PRECEDENCE - 1, resourceMapping.getOrder());
    BeanNameUrlHandlerMapping beanNameMapping = appContext.getBean(BeanNameUrlHandlerMapping.class);
    assertNotNull(beanNameMapping);
    assertEquals(2, beanNameMapping.getOrder());
    ResourceUrlProvider urlProvider = appContext.getBean(ResourceUrlProvider.class);
    assertNotNull(urlProvider);
    Map<String, MappedInterceptor> beans = appContext.getBeansOfType(MappedInterceptor.class);
    List<Class<?>> interceptors = beans.values().stream().map(mappedInterceptor -> mappedInterceptor.getInterceptor().getClass()).collect(Collectors.toList());
    assertThat(interceptors, containsInAnyOrder(ConversionServiceExposingInterceptor.class, ResourceUrlProviderExposingInterceptor.class));
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setRequestURI("/resources/foo.css");
    request.setMethod("GET");
    HandlerExecutionChain chain = resourceMapping.getHandler(request);
    assertNotNull(chain);
    assertTrue(chain.getHandler() instanceof ResourceHttpRequestHandler);
    MockHttpServletResponse response = new MockHttpServletResponse();
    for (HandlerInterceptor interceptor : chain.getInterceptors()) {
        interceptor.preHandle(request, response, chain.getHandler());
    }
    ModelAndView mv = adapter.handle(request, response, chain.getHandler());
    assertNull(mv);
}
Also used : MappedInterceptor(org.springframework.web.servlet.handler.MappedInterceptor) LocaleContextHolder(org.springframework.context.i18n.LocaleContextHolder) Arrays(java.util.Arrays) RequestParam(org.springframework.web.bind.annotation.RequestParam) Validator(org.springframework.validation.Validator) ResourceUrlProvider(org.springframework.web.servlet.resource.ResourceUrlProvider) InvocableHandlerMethod(org.springframework.web.method.support.InvocableHandlerMethod) MockRequestDispatcher(org.springframework.mock.web.test.MockRequestDispatcher) CacheControl(org.springframework.http.CacheControl) NativeWebRequest(org.springframework.web.context.request.NativeWebRequest) ServletWebRequest(org.springframework.web.context.request.ServletWebRequest) HandlerMethod(org.springframework.web.method.HandlerMethod) MvcUriComponentsBuilder(org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder) Map(java.util.Map) LocalValidatorFactoryBean(org.springframework.validation.beanvalidation.LocalValidatorFactoryBean) ContentNegotiatingViewResolver(org.springframework.web.servlet.view.ContentNegotiatingViewResolver) SpringBeanPreparerFactory(org.springframework.web.servlet.view.tiles3.SpringBeanPreparerFactory) MappingJackson2XmlHttpMessageConverter(org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter) PathResourceResolver(org.springframework.web.servlet.resource.PathResourceResolver) ResourceTransformer(org.springframework.web.servlet.resource.ResourceTransformer) RequestDispatcher(javax.servlet.RequestDispatcher) NotNull(javax.validation.constraints.NotNull) TypeMismatchException(org.springframework.beans.TypeMismatchException) StandardCharsets(java.nio.charset.StandardCharsets) NumberFormat(org.springframework.format.annotation.NumberFormat) MockServletContext(org.springframework.mock.web.test.MockServletContext) CssLinkResourceTransformer(org.springframework.web.servlet.resource.CssLinkResourceTransformer) ResourceResolver(org.springframework.web.servlet.resource.ResourceResolver) LocaleChangeInterceptor(org.springframework.web.servlet.i18n.LocaleChangeInterceptor) DeferredResultProcessingInterceptor(org.springframework.web.context.request.async.DeferredResultProcessingInterceptor) ScriptTemplateViewResolver(org.springframework.web.servlet.view.script.ScriptTemplateViewResolver) RequestMappingHandlerMapping(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping) TilesConfigurer(org.springframework.web.servlet.view.tiles3.TilesConfigurer) RequestMappingHandlerAdapter(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter) Ordered(org.springframework.core.Ordered) Errors(org.springframework.validation.Errors) ResourceUrlProviderExposingInterceptor(org.springframework.web.servlet.resource.ResourceUrlProviderExposingInterceptor) XmlMapper(com.fasterxml.jackson.dataformat.xml.XmlMapper) AbstractJackson2HttpMessageConverter(org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter) BindingResult(org.springframework.validation.BindingResult) FreeMarkerViewResolver(org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver) CachingResourceResolver(org.springframework.web.servlet.resource.CachingResourceResolver) CacheManager(org.springframework.cache.CacheManager) HandlerInterceptor(org.springframework.web.servlet.HandlerInterceptor) ConversionService(org.springframework.core.convert.ConversionService) Before(org.junit.Before) Validated(org.springframework.validation.annotation.Validated) ViewResolver(org.springframework.web.servlet.ViewResolver) XmlBeanDefinitionReader(org.springframework.beans.factory.xml.XmlBeanDefinitionReader) PathMatcher(org.springframework.util.PathMatcher) ViewResolverComposite(org.springframework.web.servlet.view.ViewResolverComposite) Target(java.lang.annotation.Target) Test(org.junit.Test) WebJarsResourceResolver(org.springframework.web.servlet.resource.WebJarsResourceResolver) BeanNameViewResolver(org.springframework.web.servlet.view.BeanNameViewResolver) GroovyMarkupViewResolver(org.springframework.web.servlet.view.groovy.GroovyMarkupViewResolver) ThemeChangeInterceptor(org.springframework.web.servlet.theme.ThemeChangeInterceptor) FormattingConversionServiceFactoryBean(org.springframework.format.support.FormattingConversionServiceFactoryBean) UrlPathHelper(org.springframework.web.util.UrlPathHelper) GenericWebApplicationContext(org.springframework.web.context.support.GenericWebApplicationContext) Assert(org.junit.Assert) VersionResourceResolver(org.springframework.web.servlet.resource.VersionResourceResolver) Date(java.util.Date) AppCacheManifestTransformer(org.springframework.web.servlet.resource.AppCacheManifestTransformer) HandlerExecutionChain(org.springframework.web.servlet.HandlerExecutionChain) InternalResourceView(org.springframework.web.servlet.view.InternalResourceView) DeserializationFeature(com.fasterxml.jackson.databind.DeserializationFeature) DateTimeFormat(org.springframework.format.annotation.DateTimeFormat) RedirectView(org.springframework.web.servlet.view.RedirectView) Locale(java.util.Locale) SimpleUrlHandlerMapping(org.springframework.web.servlet.handler.SimpleUrlHandlerMapping) Method(java.lang.reflect.Method) UnresolvingLocaleDefinitionsFactory(org.apache.tiles.definition.UnresolvingLocaleDefinitionsFactory) Collection(java.util.Collection) MediaType(org.springframework.http.MediaType) WebApplicationContext(org.springframework.web.context.WebApplicationContext) ISO(org.springframework.format.annotation.DateTimeFormat.ISO) Collectors(java.util.stream.Collectors) ModelAndView(org.springframework.web.servlet.ModelAndView) List(java.util.List) ConcurrentMapCache(org.springframework.cache.concurrent.ConcurrentMapCache) UserRoleAuthorizationInterceptor(org.springframework.web.servlet.handler.UserRoleAuthorizationInterceptor) HttpMessageConverter(org.springframework.http.converter.HttpMessageConverter) ConcurrentTaskExecutor(org.springframework.scheduling.concurrent.ConcurrentTaskExecutor) ConversionServiceExposingInterceptor(org.springframework.web.servlet.handler.ConversionServiceExposingInterceptor) FreeMarkerConfigurer(org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer) DeferredResultProcessingInterceptorAdapter(org.springframework.web.context.request.async.DeferredResultProcessingInterceptorAdapter) CachingResourceTransformer(org.springframework.web.servlet.resource.CachingResourceTransformer) CallableProcessingInterceptorAdapter(org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter) ContentVersionStrategy(org.springframework.web.servlet.resource.ContentVersionStrategy) GroovyMarkupConfigurer(org.springframework.web.servlet.view.groovy.GroovyMarkupConfigurer) MappedInterceptor(org.springframework.web.servlet.handler.MappedInterceptor) Cache(org.springframework.cache.Cache) ClassPathResource(org.springframework.core.io.ClassPathResource) InternalResourceViewResolver(org.springframework.web.servlet.view.InternalResourceViewResolver) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) DirectFieldAccessor(org.springframework.beans.DirectFieldAccessor) Controller(org.springframework.stereotype.Controller) AbstractHandlerMapping(org.springframework.web.servlet.handler.AbstractHandlerMapping) Retention(java.lang.annotation.Retention) MapperFeature(com.fasterxml.jackson.databind.MapperFeature) DefaultServletHttpRequestHandler(org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler) CompositeUriComponentsContributor(org.springframework.web.method.support.CompositeUriComponentsContributor) ScriptTemplateConfigurer(org.springframework.web.servlet.view.script.ScriptTemplateConfigurer) SimpleControllerHandlerAdapter(org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter) HttpRequestHandlerAdapter(org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter) CallableProcessingInterceptor(org.springframework.web.context.request.async.CallableProcessingInterceptor) MockHttpServletResponse(org.springframework.mock.web.test.MockHttpServletResponse) GzipResourceResolver(org.springframework.web.servlet.resource.GzipResourceResolver) TilesViewResolver(org.springframework.web.servlet.view.tiles3.TilesViewResolver) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Matchers(org.hamcrest.Matchers) CorsConfiguration(org.springframework.web.cors.CorsConfiguration) ParameterizableViewController(org.springframework.web.servlet.mvc.ParameterizableViewController) ElementType(java.lang.annotation.ElementType) TimeUnit(java.util.concurrent.TimeUnit) LocalDate(org.joda.time.LocalDate) ResourceHttpRequestHandler(org.springframework.web.servlet.resource.ResourceHttpRequestHandler) BeanNameUrlHandlerMapping(org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping) ContentNegotiationManager(org.springframework.web.accept.ContentNegotiationManager) FixedVersionStrategy(org.springframework.web.servlet.resource.FixedVersionStrategy) Comparator(java.util.Comparator) Collections(java.util.Collections) RetentionPolicy(java.lang.annotation.RetentionPolicy) MockHttpServletRequest(org.springframework.mock.web.test.MockHttpServletRequest) ResourceHttpRequestHandler(org.springframework.web.servlet.resource.ResourceHttpRequestHandler) HttpRequestHandlerAdapter(org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter) BeanNameUrlHandlerMapping(org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping) HandlerInterceptor(org.springframework.web.servlet.HandlerInterceptor) MockHttpServletRequest(org.springframework.mock.web.test.MockHttpServletRequest) ModelAndView(org.springframework.web.servlet.ModelAndView) SimpleUrlHandlerMapping(org.springframework.web.servlet.handler.SimpleUrlHandlerMapping) ResourceUrlProvider(org.springframework.web.servlet.resource.ResourceUrlProvider) ContentNegotiationManager(org.springframework.web.accept.ContentNegotiationManager) ResourceUrlProviderExposingInterceptor(org.springframework.web.servlet.resource.ResourceUrlProviderExposingInterceptor) ConversionServiceExposingInterceptor(org.springframework.web.servlet.handler.ConversionServiceExposingInterceptor) HandlerExecutionChain(org.springframework.web.servlet.HandlerExecutionChain) RequestMappingHandlerMapping(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping) MockHttpServletResponse(org.springframework.mock.web.test.MockHttpServletResponse) Test(org.junit.Test)

Aggregations

ResourceHttpRequestHandler (org.springframework.web.servlet.resource.ResourceHttpRequestHandler)15 Test (org.junit.Test)10 SimpleUrlHandlerMapping (org.springframework.web.servlet.handler.SimpleUrlHandlerMapping)9 CachingResourceResolver (org.springframework.web.servlet.resource.CachingResourceResolver)7 CachingResourceTransformer (org.springframework.web.servlet.resource.CachingResourceTransformer)7 CssLinkResourceTransformer (org.springframework.web.servlet.resource.CssLinkResourceTransformer)7 PathResourceResolver (org.springframework.web.servlet.resource.PathResourceResolver)7 ResourceResolver (org.springframework.web.servlet.resource.ResourceResolver)7 ResourceTransformer (org.springframework.web.servlet.resource.ResourceTransformer)7 VersionResourceResolver (org.springframework.web.servlet.resource.VersionResourceResolver)7 WebJarsResourceResolver (org.springframework.web.servlet.resource.WebJarsResourceResolver)7 AppCacheManifestTransformer (org.springframework.web.servlet.resource.AppCacheManifestTransformer)5 ConcurrentMapCache (org.springframework.cache.concurrent.ConcurrentMapCache)3 MockHttpServletRequest (org.springframework.mock.web.test.MockHttpServletRequest)3 LinkedHashMap (java.util.LinkedHashMap)2 List (java.util.List)2 Map (java.util.Map)2 ClassPathResource (org.springframework.core.io.ClassPathResource)2 ContentNegotiationManager (org.springframework.web.accept.ContentNegotiationManager)2 NativeWebRequest (org.springframework.web.context.request.NativeWebRequest)2