Search in sources :

Example 1 with ContentNegotiationManager

use of org.springframework.web.accept.ContentNegotiationManager in project spring-framework by spring-projects.

the class ViewResolutionTests method testContentNegotiation.

@Test
public void testContentNegotiation() throws Exception {
    Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
    marshaller.setClassesToBeBound(Person.class);
    List<View> viewList = new ArrayList<>();
    viewList.add(new MappingJackson2JsonView());
    viewList.add(new MarshallingView(marshaller));
    ContentNegotiationManager manager = new ContentNegotiationManager(new HeaderContentNegotiationStrategy(), new FixedContentNegotiationStrategy(MediaType.TEXT_HTML));
    ContentNegotiatingViewResolver cnViewResolver = new ContentNegotiatingViewResolver();
    cnViewResolver.setDefaultViews(viewList);
    cnViewResolver.setContentNegotiationManager(manager);
    cnViewResolver.afterPropertiesSet();
    MockMvc mockMvc = standaloneSetup(new PersonController()).setViewResolvers(cnViewResolver, new InternalResourceViewResolver()).build();
    mockMvc.perform(get("/person/Corea")).andExpect(status().isOk()).andExpect(model().size(1)).andExpect(model().attributeExists("person")).andExpect(forwardedUrl("person/show"));
    mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_JSON)).andExpect(jsonPath("$.person.name").value("Corea"));
    mockMvc.perform(get("/person/Corea").accept(MediaType.APPLICATION_XML)).andExpect(status().isOk()).andExpect(content().contentType(MediaType.APPLICATION_XML)).andExpect(xpath("/person/name/text()").string(equalTo("Corea")));
}
Also used : ArrayList(java.util.ArrayList) Jaxb2Marshaller(org.springframework.oxm.jaxb.Jaxb2Marshaller) FixedContentNegotiationStrategy(org.springframework.web.accept.FixedContentNegotiationStrategy) View(org.springframework.web.servlet.View) MappingJackson2JsonView(org.springframework.web.servlet.view.json.MappingJackson2JsonView) MarshallingView(org.springframework.web.servlet.view.xml.MarshallingView) MappingJackson2JsonView(org.springframework.web.servlet.view.json.MappingJackson2JsonView) ContentNegotiationManager(org.springframework.web.accept.ContentNegotiationManager) MarshallingView(org.springframework.web.servlet.view.xml.MarshallingView) ContentNegotiatingViewResolver(org.springframework.web.servlet.view.ContentNegotiatingViewResolver) HeaderContentNegotiationStrategy(org.springframework.web.accept.HeaderContentNegotiationStrategy) MockMvc(org.springframework.test.web.servlet.MockMvc) InternalResourceViewResolver(org.springframework.web.servlet.view.InternalResourceViewResolver) Test(org.junit.Test)

Example 2 with ContentNegotiationManager

use of org.springframework.web.accept.ContentNegotiationManager 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 3 with ContentNegotiationManager

use of org.springframework.web.accept.ContentNegotiationManager 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)

Example 4 with ContentNegotiationManager

use of org.springframework.web.accept.ContentNegotiationManager in project spring-framework by spring-projects.

the class ViewResolverRegistryTests method setUp.

@Before
public void setUp() {
    StaticWebApplicationContext context = new StaticWebApplicationContext();
    context.registerSingleton("freeMarkerConfigurer", FreeMarkerConfigurer.class);
    context.registerSingleton("tilesConfigurer", TilesConfigurer.class);
    context.registerSingleton("groovyMarkupConfigurer", GroovyMarkupConfigurer.class);
    context.registerSingleton("scriptTemplateConfigurer", ScriptTemplateConfigurer.class);
    this.registry = new ViewResolverRegistry();
    this.registry.setApplicationContext(context);
    this.registry.setContentNegotiationManager(new ContentNegotiationManager());
}
Also used : ContentNegotiationManager(org.springframework.web.accept.ContentNegotiationManager) StaticWebApplicationContext(org.springframework.web.context.support.StaticWebApplicationContext) Before(org.junit.Before)

Example 5 with ContentNegotiationManager

use of org.springframework.web.accept.ContentNegotiationManager in project spring-framework by spring-projects.

the class ContentNegotiationConfigurerTests method addMediaTypes.

@Test
public void addMediaTypes() throws Exception {
    this.configurer.mediaTypes(Collections.singletonMap("json", MediaType.APPLICATION_JSON));
    ContentNegotiationManager manager = this.configurer.getContentNegotiationManager();
    this.servletRequest.setRequestURI("/flower.json");
    assertEquals(Arrays.asList(MediaType.APPLICATION_JSON), manager.resolveMediaTypes(this.webRequest));
}
Also used : ContentNegotiationManager(org.springframework.web.accept.ContentNegotiationManager) Test(org.junit.Test)

Aggregations

ContentNegotiationManager (org.springframework.web.accept.ContentNegotiationManager)24 Test (org.junit.Test)23 MediaType (org.springframework.http.MediaType)8 ViewResolver (org.springframework.web.servlet.ViewResolver)8 Locale (java.util.Locale)7 View (org.springframework.web.servlet.View)7 MockHttpServletRequest (org.springframework.mock.web.test.MockHttpServletRequest)4 MockServletContext (org.springframework.mock.web.test.MockServletContext)4 NativeWebRequest (org.springframework.web.context.request.NativeWebRequest)4 ServletWebRequest (org.springframework.web.context.request.ServletWebRequest)4 RequestMappingHandlerMapping (org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping)4 ContentNegotiatingViewResolver (org.springframework.web.servlet.view.ContentNegotiatingViewResolver)4 ClassPathResource (org.springframework.core.io.ClassPathResource)3 FixedContentNegotiationStrategy (org.springframework.web.accept.FixedContentNegotiationStrategy)3 PathExtensionContentNegotiationStrategy (org.springframework.web.accept.PathExtensionContentNegotiationStrategy)3 HandlerExecutionChain (org.springframework.web.servlet.HandlerExecutionChain)3 BeanNameViewResolver (org.springframework.web.servlet.view.BeanNameViewResolver)3 InternalResourceViewResolver (org.springframework.web.servlet.view.InternalResourceViewResolver)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 Method (java.lang.reflect.Method)2