@Bean public ViewResolver contentNegotiatingViewResolver() { logger.debug("Configuring the ContentNegotiatingViewResolver"); ContentNegotiatingViewResolver viewResolver = new ContentNegotiatingViewResolver(); List<ViewResolver> viewResolvers = new ArrayList<ViewResolver>(); UrlBasedViewResolver urlBasedViewResolver = new UrlBasedViewResolver(); urlBasedViewResolver.setViewClass(JstlView.class); urlBasedViewResolver.setSuffix(".html"); viewResolvers.add(urlBasedViewResolver); viewResolver.setViewResolvers(viewResolvers); List<View> defaultViews = new ArrayList<View>(); defaultViews.add(new MappingJackson2JsonView()); viewResolver.setDefaultViews(defaultViews); return viewResolver; }
private ViewResolver getViewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver() { @Override protected AbstractUrlBasedView buildView(String viewName) throws Exception { String suffix = getSuffix(); if (suffix != null && suffix.length() > 0 && viewName.endsWith(suffix)) { viewName = viewName.substring(0, viewName.length() - suffix.length()); } return super.buildView(viewName); } }; viewResolver.setPrefix("/"); viewResolver.setSuffix(""); return viewResolver; }
private List<View> getCandidateViews(String viewName, Locale locale, List<MediaType> requestedMediaTypes) throws Exception { List<View> candidateViews = new ArrayList<View>(); for (ViewResolver viewResolver : this.viewResolvers) { View view = viewResolver.resolveViewName(viewName, locale); if (view != null) { candidateViews.add(view); } for (MediaType requestedMediaType : requestedMediaTypes) { List<String> extensions = this.contentNegotiationManager.resolveFileExtensions(requestedMediaType); for (String extension : extensions) { String viewNameWithExtension = viewName + "." + extension; view = viewResolver.resolveViewName(viewNameWithExtension, locale); if (view != null) { candidateViews.add(view); } } } } if (!CollectionUtils.isEmpty(this.defaultViews)) { candidateViews.addAll(this.defaultViews); } return candidateViews; }
/** * Register a {@link ViewResolverComposite} that contains a chain of view resolvers * to use for view resolution. * By default this resolver is ordered at 0 unless content negotiation view * resolution is used in which case the order is raised to * {@link org.springframework.core.Ordered#HIGHEST_PRECEDENCE * Ordered.HIGHEST_PRECEDENCE}. * <p>If no other resolvers are configured, * {@link ViewResolverComposite#resolveViewName(String, Locale)} returns null in order * to allow other potential {@link ViewResolver} beans to resolve views. * @since 4.1 */ @Bean public ViewResolver mvcViewResolver() { ViewResolverRegistry registry = new ViewResolverRegistry(); registry.setContentNegotiationManager(mvcContentNegotiationManager()); registry.setApplicationContext(this.applicationContext); configureViewResolvers(registry); if (registry.getViewResolvers().isEmpty()) { String[] names = BeanFactoryUtils.beanNamesForTypeIncludingAncestors( this.applicationContext, ViewResolver.class, true, false); if (names.length == 1) { registry.getViewResolvers().add(new InternalResourceViewResolver()); } } ViewResolverComposite composite = new ViewResolverComposite(); composite.setOrder(registry.getOrder()); composite.setViewResolvers(registry.getViewResolvers()); composite.setApplicationContext(this.applicationContext); composite.setServletContext(this.servletContext); return composite; }
@Test public void resolveViewNameWithPathExtension() throws Exception { request.setRequestURI("/test.xls"); ViewResolver viewResolverMock = mock(ViewResolver.class); viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock)); viewResolver.afterPropertiesSet(); View viewMock = mock(View.class, "application_xls"); String viewName = "view"; Locale locale = Locale.ENGLISH; given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(null); given(viewResolverMock.resolveViewName(viewName + ".xls", locale)).willReturn(viewMock); given(viewMock.getContentType()).willReturn("application/vnd.ms-excel"); View result = viewResolver.resolveViewName(viewName, locale); assertSame("Invalid view", viewMock, result); }
@Test public void resolveViewNameWithAcceptHeader() throws Exception { request.addHeader("Accept", "application/vnd.ms-excel"); Map<String, MediaType> mapping = Collections.singletonMap("xls", MediaType.valueOf("application/vnd.ms-excel")); MappingMediaTypeFileExtensionResolver extensionsResolver = new MappingMediaTypeFileExtensionResolver(mapping); ContentNegotiationManager manager = new ContentNegotiationManager(new HeaderContentNegotiationStrategy()); manager.addFileExtensionResolvers(extensionsResolver); viewResolver.setContentNegotiationManager(manager); ViewResolver viewResolverMock = mock(ViewResolver.class); viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock)); View viewMock = mock(View.class, "application_xls"); String viewName = "view"; Locale locale = Locale.ENGLISH; given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(null); given(viewResolverMock.resolveViewName(viewName + ".xls", locale)).willReturn(viewMock); given(viewMock.getContentType()).willReturn("application/vnd.ms-excel"); View result = viewResolver.resolveViewName(viewName, locale); assertSame("Invalid view", viewMock, result); }
@Test public void resolveViewNameWithRequestParameter() throws Exception { request.addParameter("format", "xls"); Map<String, MediaType> mapping = Collections.singletonMap("xls", MediaType.valueOf("application/vnd.ms-excel")); ParameterContentNegotiationStrategy paramStrategy = new ParameterContentNegotiationStrategy(mapping); viewResolver.setContentNegotiationManager(new ContentNegotiationManager(paramStrategy)); ViewResolver viewResolverMock = mock(ViewResolver.class); viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock)); viewResolver.afterPropertiesSet(); View viewMock = mock(View.class, "application_xls"); String viewName = "view"; Locale locale = Locale.ENGLISH; given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(null); given(viewResolverMock.resolveViewName(viewName + ".xls", locale)).willReturn(viewMock); given(viewMock.getContentType()).willReturn("application/vnd.ms-excel"); View result = viewResolver.resolveViewName(viewName, locale); assertSame("Invalid view", viewMock, result); }
@Test public void resolveViewNameAcceptHeader() throws Exception { request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); ViewResolver viewResolverMock1 = mock(ViewResolver.class); ViewResolver viewResolverMock2 = mock(ViewResolver.class); viewResolver.setViewResolvers(Arrays.asList(viewResolverMock1, viewResolverMock2)); viewResolver.afterPropertiesSet(); View viewMock1 = mock(View.class, "application_xml"); View viewMock2 = mock(View.class, "text_html"); String viewName = "view"; Locale locale = Locale.ENGLISH; given(viewResolverMock1.resolveViewName(viewName, locale)).willReturn(viewMock1); given(viewResolverMock2.resolveViewName(viewName, locale)).willReturn(viewMock2); given(viewMock1.getContentType()).willReturn("application/xml"); given(viewMock2.getContentType()).willReturn("text/html;charset=ISO-8859-1"); View result = viewResolver.resolveViewName(viewName, locale); assertSame("Invalid view", viewMock2, result); }
@Test public void resolveViewNameAcceptHeaderSortByQuality() throws Exception { request.addHeader("Accept", "text/plain;q=0.5, application/json"); viewResolver.setContentNegotiationManager(new ContentNegotiationManager(new HeaderContentNegotiationStrategy())); ViewResolver htmlViewResolver = mock(ViewResolver.class); ViewResolver jsonViewResolver = mock(ViewResolver.class); viewResolver.setViewResolvers(Arrays.asList(htmlViewResolver, jsonViewResolver)); View htmlView = mock(View.class, "text_html"); View jsonViewMock = mock(View.class, "application_json"); String viewName = "view"; Locale locale = Locale.ENGLISH; given(htmlViewResolver.resolveViewName(viewName, locale)).willReturn(htmlView); given(jsonViewResolver.resolveViewName(viewName, locale)).willReturn(jsonViewMock); given(htmlView.getContentType()).willReturn("text/html"); given(jsonViewMock.getContentType()).willReturn("application/json"); View result = viewResolver.resolveViewName(viewName, locale); assertSame("Invalid view", jsonViewMock, result); }
@Test public void resolveViewNameFilename() throws Exception { request.setRequestURI("/test.html"); ViewResolver viewResolverMock1 = mock(ViewResolver.class, "viewResolver1"); ViewResolver viewResolverMock2 = mock(ViewResolver.class, "viewResolver2"); viewResolver.setViewResolvers(Arrays.asList(viewResolverMock1, viewResolverMock2)); viewResolver.afterPropertiesSet(); View viewMock1 = mock(View.class, "application_xml"); View viewMock2 = mock(View.class, "text_html"); String viewName = "view"; Locale locale = Locale.ENGLISH; given(viewResolverMock1.resolveViewName(viewName, locale)).willReturn(viewMock1); given(viewResolverMock1.resolveViewName(viewName + ".html", locale)).willReturn(null); given(viewResolverMock2.resolveViewName(viewName, locale)).willReturn(null); given(viewResolverMock2.resolveViewName(viewName + ".html", locale)).willReturn(viewMock2); given(viewMock1.getContentType()).willReturn("application/xml"); given(viewMock2.getContentType()).willReturn("text/html;charset=ISO-8859-1"); View result = viewResolver.resolveViewName(viewName, locale); assertSame("Invalid view", viewMock2, result); }
@Test public void resolveViewContentTypeNull() throws Exception { request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); ViewResolver viewResolverMock = mock(ViewResolver.class); viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock)); viewResolver.afterPropertiesSet(); View viewMock = mock(View.class, "application_xml"); String viewName = "view"; Locale locale = Locale.ENGLISH; given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(viewMock); given(viewMock.getContentType()).willReturn(null); View result = viewResolver.resolveViewName(viewName, locale); assertNull("Invalid view", result); }
@Test public void resolveViewNoMatch() throws Exception { request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9"); ViewResolver viewResolverMock = mock(ViewResolver.class); viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock)); viewResolver.afterPropertiesSet(); View viewMock = mock(View.class, "application_xml"); String viewName = "view"; Locale locale = Locale.ENGLISH; given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(viewMock); given(viewMock.getContentType()).willReturn("application/pdf"); View result = viewResolver.resolveViewName(viewName, locale); assertNull("Invalid view", result); }
@Test public void resolveViewNoMatchUseUnacceptableStatus() throws Exception { viewResolver.setUseNotAcceptableStatusCode(true); request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9"); ViewResolver viewResolverMock = mock(ViewResolver.class); viewResolver.setViewResolvers(Collections.singletonList(viewResolverMock)); viewResolver.afterPropertiesSet(); View viewMock = mock(View.class, "application_xml"); String viewName = "view"; Locale locale = Locale.ENGLISH; given(viewResolverMock.resolveViewName(viewName, locale)).willReturn(viewMock); given(viewMock.getContentType()).willReturn("application/pdf"); View result = viewResolver.resolveViewName(viewName, locale); assertNotNull("Invalid view", result); MockHttpServletResponse response = new MockHttpServletResponse(); result.render(null, request, response); assertEquals("Invalid status code set", 406, response.getStatus()); }
@Test public void nestedViewResolverIsNotSpringBean() throws Exception { StaticWebApplicationContext webAppContext = new StaticWebApplicationContext(); webAppContext.setServletContext(new MockServletContext()); webAppContext.refresh(); InternalResourceViewResolver nestedResolver = new InternalResourceViewResolver(); nestedResolver.setApplicationContext(webAppContext); nestedResolver.setViewClass(InternalResourceView.class); viewResolver.setViewResolvers(new ArrayList<ViewResolver>(Arrays.asList(nestedResolver))); FixedContentNegotiationStrategy fixedStrategy = new FixedContentNegotiationStrategy(MediaType.TEXT_HTML); viewResolver.setContentNegotiationManager(new ContentNegotiationManager(fixedStrategy)); viewResolver.afterPropertiesSet(); String viewName = "view"; Locale locale = Locale.ENGLISH; View result = viewResolver.resolveViewName(viewName, locale); assertNotNull("Invalid view", result); }
@Test public void testContentNegotiationManager() throws Exception { loadBeanDefinitions("mvc-config-content-negotiation-manager.xml", 15); RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class); ContentNegotiationManager manager = mapping.getContentNegotiationManager(); MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo.xml"); NativeWebRequest webRequest = new ServletWebRequest(request); assertEquals(Arrays.asList(MediaType.valueOf("application/rss+xml")), manager.resolveMediaTypes(webRequest)); ViewResolverComposite compositeResolver = this.appContext.getBean(ViewResolverComposite.class); assertNotNull(compositeResolver); assertEquals("Actual: " + compositeResolver.getViewResolvers(), 1, compositeResolver.getViewResolvers().size()); ViewResolver resolver = compositeResolver.getViewResolvers().get(0); assertEquals(ContentNegotiatingViewResolver.class, resolver.getClass()); ContentNegotiatingViewResolver cnvr = (ContentNegotiatingViewResolver) resolver; assertSame(manager, cnvr.getContentNegotiationManager()); }
@Test public void testViewResolutionWithContentNegotiation() throws Exception { loadBeanDefinitions("mvc-config-view-resolution-content-negotiation.xml", 7); ViewResolverComposite compositeResolver = this.appContext.getBean(ViewResolverComposite.class); assertNotNull(compositeResolver); assertEquals(1, compositeResolver.getViewResolvers().size()); assertEquals(Ordered.HIGHEST_PRECEDENCE, compositeResolver.getOrder()); List<ViewResolver> resolvers = compositeResolver.getViewResolvers(); assertEquals(ContentNegotiatingViewResolver.class, resolvers.get(0).getClass()); ContentNegotiatingViewResolver cnvr = (ContentNegotiatingViewResolver) resolvers.get(0); assertEquals(7, cnvr.getViewResolvers().size()); assertEquals(1, cnvr.getDefaultViews().size()); assertTrue(cnvr.isUseNotAcceptableStatusCode()); String beanName = "contentNegotiationManager"; DirectFieldAccessor accessor = new DirectFieldAccessor(cnvr); ContentNegotiationManager manager = (ContentNegotiationManager) accessor.getPropertyValue(beanName); assertNotNull(manager); assertSame(manager, this.appContext.getBean(ContentNegotiationManager.class)); }
@Test public void renderNonWebAppTemplate() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( ThymeleafAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); assertThat(context.getBeanNamesForType(ViewResolver.class).length).isEqualTo(0); try { TemplateEngine engine = context.getBean(TemplateEngine.class); Context attrs = new Context(Locale.UK, Collections.singletonMap("greeting", "Hello World")); String result = engine.process("message", attrs); assertThat(result).contains("Hello World"); } finally { context.close(); } }
@Bean public ViewResolver viewResolver() { ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver(); List<View> defaultViews = new ArrayList<View>(); defaultViews.add(new MappingJackson2JsonView()); resolver.setDefaultViews(defaultViews); resolver.setOrder(0); List<ViewResolver> viewResolvers = new ArrayList<ViewResolver>(); InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver(); internalResourceViewResolver.setPrefix("/WEB-INF/view/"); internalResourceViewResolver.setSuffix(".jsp"); internalResourceViewResolver.setOrder(1); viewResolvers.add(internalResourceViewResolver); resolver.setViewResolvers(viewResolvers); return resolver; }
@Bean public ViewResolver contentNegotiatingViewResolver() { LOGGER.debug("Configuring the ContentNegotiatingViewResolver"); ContentNegotiatingViewResolver viewResolver = new ContentNegotiatingViewResolver(); List<ViewResolver> viewResolvers = new ArrayList<>(); UrlBasedViewResolver urlBasedViewResolver = new UrlBasedViewResolver(); urlBasedViewResolver.setViewClass(JstlView.class); urlBasedViewResolver.setPrefix("/WEB-INF/pages/"); urlBasedViewResolver.setSuffix(".jsp"); viewResolvers.add(urlBasedViewResolver); viewResolver.setViewResolvers(viewResolvers); List<View> defaultViews = new ArrayList<>(); defaultViews.add(new MappingJackson2JsonView()); viewResolver.setDefaultViews(defaultViews); return viewResolver; }
@Bean public ViewResolver handlebars() { HandlebarsViewResolver viewResolver = new HandlebarsViewResolver(); // add handlebars helper to get a label's literal without datatype viewResolver.registerHelper("literal", new Helper<Literal>() { @Override public Object apply(Literal literal, Options options) throws IOException { return literal.getLabel(); } }); viewResolver.setPrefix("/WEB-INF/templates/"); viewResolver.setSuffix(".hbs"); viewResolver.setFailOnMissingFile(false); return viewResolver; }
/** * 视图解析器 * velocity * 过期是由于velocity六年没有更新过了,spring官方推荐使用FreeMarker或者Thymeleaf * 后期考虑spring官方的Thymeleaf */ @Bean public ViewResolver viewResolver() { /* InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setContentType("text/html;charset=utf-8"); viewResolver.setPrefix("/static/"); viewResolver.setSuffix(".html"); return viewResolver;*/ VelocityViewResolver velocityViewResolver = new VelocityViewResolver(); velocityViewResolver.setCache(true); velocityViewResolver.setPrefix(""); velocityViewResolver.setSuffix(".html"); velocityViewResolver.setContentType("text/html;charset=utf-8"); //关于Toolbox路径问题:如何路径开始头没有/会自动加上/,所以你如果写classpath:之类的识别不了 velocityViewResolver.setToolboxConfigLocation("/WEB-INF/velocityToolBox.xml"); velocityViewResolver.setViewClass(VelocityToolboxView.class); return velocityViewResolver; }
@Test public void renderNonWebAppTemplate() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( ThymeleafAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); assertEquals(0, context.getBeanNamesForType(ViewResolver.class).length); try { TemplateEngine engine = context.getBean(TemplateEngine.class); Context attrs = new Context(Locale.UK, Collections.singletonMap("greeting", "Hello World")); String result = engine.process("message", attrs); assertThat(result, containsString("Hello World")); } finally { context.close(); } }
@Bean public ContentNegotiatingViewResolver contentNegotiatingViewResolver() { List<View> defaultViews = new ArrayList<>(2); defaultViews.add(jsonCatnapSpringView()); defaultViews.add(jsonpCatnapSpringView()); List<CatnapWrappingView> catnapViews = new ArrayList<>(2); catnapViews.add(jsonCatnapSpringView()); catnapViews.add(jsonpCatnapSpringView()); CatnapViewResolver catnapViewResolver = new CatnapViewResolver(); catnapViewResolver.setViews(catnapViews); List<ViewResolver> viewResolvers = new ArrayList<>(1); viewResolvers.add(catnapViewResolver); ContentNegotiatingViewResolver cnvr = new ContentNegotiatingViewResolver(); cnvr.setContentNegotiationManager(mvcContentNegotiationManager()); cnvr.setOrder(1); cnvr.setDefaultViews(defaultViews); cnvr.setViewResolvers(viewResolvers); return cnvr; }
/** Fetch a Spring View, initializing the resolvers if necessary. */ protected View resolveView(FrameJob task, String viewName) { if (resolvers == null) { ApplicationContext ctx = task.getResource(ApplicationContext.class); Map<String, ViewResolver> beans = BeanFactoryUtils.beansOfTypeIncludingAncestors(ctx, ViewResolver.class, true, false); resolvers = new ArrayList<ViewResolver>(beans.values()); } try { for (ViewResolver vr : resolvers) { View v = vr.resolveViewName(viewName, LocaleContextHolder.getLocale()); if (v != null) { return v; } } return null; } catch (Exception ex) { throw new RuntimeException("Unable to resolve view: " + viewName, ex); } }
@Bean public ViewResolver contentNegotiatingViewResolver( ContentNegotiationManager manager) { List< ViewResolver > resolvers = new ArrayList<ViewResolver>(); UrlBasedViewResolver viewResolver = new UrlBasedViewResolver(); viewResolver.setViewClass(TilesView.class); resolvers.add(viewResolver); JsonViewResolver r2 = new JsonViewResolver(); resolvers.add(r2); ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver(); resolver.setViewResolvers(resolvers); resolver.setContentNegotiationManager(manager); return resolver; }
@Test @Ignore public void renderNonWebAppTemplate() throws Exception { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( Jade4JAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); assertEquals(0, context.getBeanNamesForType(ViewResolver.class).length); try { JadeConfiguration engine = this.context.getBean(JadeConfiguration.class); JadeTemplate template = engine.getTemplate("demo.jade"); Map<String, Object> params = params(); String result = engine.renderTemplate(template, params); assertThat(result, containsString("With user")); } finally { context.close(); } }
public View resolveViewName(String viewName, Locale locale) throws Exception { String viewType = this.defaultViewType; viewName = StringUtils.stripStart(viewName, "/"); int index = viewName.lastIndexOf("."); if(index > 0){ viewType = viewName.substring(index + 1); if(!this.viewResolvers.containsKey(viewType)){ viewType = this.defaultViewType; } viewName = viewName.substring(0, index); } ViewResolver viewResolver = this.viewResolvers.get(viewType); return viewResolver.resolveViewName(viewName, locale); }