org.springframework.web.servlet.View Java Examples

The following examples show how to use org.springframework.web.servlet.View. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ContentNegotiatingViewResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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());
}
 
Example #2
Source File: RequestMappingHandlerAdapter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private ModelAndView getModelAndView(ModelAndViewContainer mavContainer,
		ModelFactory modelFactory, NativeWebRequest webRequest) throws Exception {

	modelFactory.updateModel(webRequest, mavContainer);
	if (mavContainer.isRequestHandled()) {
		return null;
	}
	ModelMap model = mavContainer.getModel();
	ModelAndView mav = new ModelAndView(mavContainer.getViewName(), model);
	if (!mavContainer.isViewReference()) {
		mav.setView((View) mavContainer.getView());
	}
	if (model instanceof RedirectAttributes) {
		Map<String, ?> flashAttributes = ((RedirectAttributes) model).getFlashAttributes();
		HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
		RequestContextUtils.getOutputFlashMap(request).putAll(flashAttributes);
	}
	return mav;
}
 
Example #3
Source File: BeanNameViewResolver.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public View resolveViewName(String viewName, Locale locale) throws BeansException {
	ApplicationContext context = getApplicationContext();
	if (!context.containsBean(viewName)) {
		if (logger.isDebugEnabled()) {
			logger.debug("No matching bean found for view name '" + viewName + "'");
		}
		// Allow for ViewResolver chaining...
		return null;
	}
	if (!context.isTypeMatch(viewName, View.class)) {
		if (logger.isDebugEnabled()) {
			logger.debug("Found matching bean for view name '" + viewName +
					"' - to be ignored since it does not implement View");
		}
		// Since we're looking into the general ApplicationContext here,
		// let's accept this as a non-match and allow for chaining as well...
		return null;
	}
	return context.getBean(viewName, View.class);
}
 
Example #4
Source File: ViewResolverTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private void doTestUrlBasedViewResolverWithPrefixes(UrlBasedViewResolver vr) throws Exception {
	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	wac.setServletContext(new MockServletContext());
	wac.refresh();
	vr.setPrefix("/WEB-INF/");
	vr.setSuffix(".jsp");
	vr.setApplicationContext(wac);

	View view = vr.resolveViewName("example1", Locale.getDefault());
	assertEquals("Correct view class", JstlView.class, view.getClass());
	assertEquals("Correct URL", "/WEB-INF/example1.jsp", ((InternalResourceView) view).getUrl());

	view = vr.resolveViewName("example2", Locale.getDefault());
	assertEquals("Correct view class", JstlView.class, view.getClass());
	assertEquals("Correct URL", "/WEB-INF/example2.jsp", ((InternalResourceView) view).getUrl());

	view = vr.resolveViewName("redirect:myUrl", Locale.getDefault());
	assertEquals("Correct view class", RedirectView.class, view.getClass());
	assertEquals("Correct URL", "myUrl", ((RedirectView) view).getUrl());

	view = vr.resolveViewName("forward:myUrl", Locale.getDefault());
	assertEquals("Correct view class", InternalResourceView.class, view.getClass());
	assertEquals("Correct URL", "myUrl", ((InternalResourceView) view).getUrl());
}
 
Example #5
Source File: ContentNegotiatingViewResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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<>(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);
}
 
Example #6
Source File: ContentNegotiatingViewResolver.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
	RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
	Assert.isInstanceOf(ServletRequestAttributes.class, attrs);
	List<MediaType> requestedMediaTypes = getMediaTypes(((ServletRequestAttributes) attrs).getRequest());
	if (requestedMediaTypes != null) {
		List<View> candidateViews = getCandidateViews(viewName, locale, requestedMediaTypes);
		View bestView = getBestView(candidateViews, requestedMediaTypes, attrs);
		if (bestView != null) {
			return bestView;
		}
	}
	if (this.useNotAcceptableStatusCode) {
		if (logger.isDebugEnabled()) {
			logger.debug("No acceptable view found; returning 406 (Not Acceptable) status code");
		}
		return NOT_ACCEPTABLE_VIEW;
	}
	else {
		logger.debug("No acceptable view found; returning null");
		return null;
	}
}
 
Example #7
Source File: ContentNegotiatingViewResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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);
}
 
Example #8
Source File: ServletAnnotationControllerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public ModelAndView resolveModelAndView(Method handlerMethod,
		Class handlerType,
		Object returnValue,
		ExtendedModelMap implicitModel,
		NativeWebRequest webRequest) {
	if (returnValue instanceof MySpecialArg) {
		return new ModelAndView(new View() {
			@Override
			public String getContentType() {
				return "text/html";
			}

			@Override
			public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
					throws Exception {
				response.getWriter().write("myValue");
			}

		});
	}
	return UNRESOLVED;
}
 
Example #9
Source File: CatnapViewResolver.java    From catnap with Apache License 2.0 6 votes vote down vote up
@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
    if (views.isEmpty()) {
        logger.warn("No views configured for view resolver [{}]", getClass().getName());
    }

    View view = null;

    if (view == null) {
        view = resolveViewWithHrefSuffix(viewName, locale);
    }

    if (view == null) {
        view = resolveViewWithAcceptHeader(viewName, locale);
    }

    return view;
}
 
Example #10
Source File: ContentNegotiatingViewResolverTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #11
Source File: ContentNegotiatingViewResolverTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #12
Source File: ContentNegotiatingViewResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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);
}
 
Example #13
Source File: PathVariableMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void resolveArgumentWithExistingPathVars() throws Exception {
	Map<String, String> uriTemplateVars = new HashMap<>();
	uriTemplateVars.put("name", "value");
	request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars);

	uriTemplateVars.put("oldName", "oldValue");
	request.setAttribute(View.PATH_VARIABLES, uriTemplateVars);

	String result = (String) resolver.resolveArgument(paramNamedString, mavContainer, webRequest, null);
	assertEquals("PathVariable not resolved correctly", "value", result);

	@SuppressWarnings("unchecked")
	Map<String, Object> pathVars = (Map<String, Object>) request.getAttribute(View.PATH_VARIABLES);
	assertNotNull(pathVars);
	assertEquals(2, pathVars.size());
	assertEquals("value", pathVars.get("name"));
	assertEquals("oldValue", pathVars.get("oldName"));
}
 
Example #14
Source File: ContentNegotiatingViewResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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);
}
 
Example #15
Source File: ContentNegotiatingViewResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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);
}
 
Example #16
Source File: ContentNegotiatingViewResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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);
}
 
Example #17
Source File: ContentNegotiatingViewResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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);
}
 
Example #18
Source File: ContentNegotiatingViewResolverTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #19
Source File: ProfileController.java    From forum with MIT License 6 votes vote down vote up
@PostMapping("profile")
public View addTask(@RequestParam("category") String category, @RequestParam("title") String title,
                    @RequestParam("content") String content, @RequestParam("code") String code,
                    @RequestParam("id_user") String id_user, HttpServletRequest request) {
    Topic topic = new Topic();
    topic.setCategory(category);

    // I know that it can be blank field, but I did it on purpose to find out about Optionals:
    if (Objects.equals(code, ""))
        topic.setCode(null);
    else
        topic.setCode(code);

    topic.setContent(content);
    topic.setTitle(title);
    topic.setCreatedDate(LocalDateTime.now());
    topic.setUser(userRepository.getUserById(Long.parseLong(id_user)));

    topicRepository.save(topic);
    String contextPath = request.getContextPath();
    return new RedirectView(contextPath + "/profile");
}
 
Example #20
Source File: ViewResolverTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testCacheRemoval() throws Exception {
	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	wac.setServletContext(new MockServletContext());
	wac.refresh();
	InternalResourceViewResolver vr = new InternalResourceViewResolver();
	vr.setViewClass(JstlView.class);
	vr.setApplicationContext(wac);

	View view = vr.resolveViewName("example1", Locale.getDefault());
	View cached = vr.resolveViewName("example1", Locale.getDefault());
	if (view != cached) {
		fail("Caching doesn't work");
	}

	vr.removeFromCache("example1", Locale.getDefault());
	cached = vr.resolveViewName("example1", Locale.getDefault());
	if (view == cached) {
		// the chance of having the same reference (hashCode) twice if negligible).
		fail("View wasn't removed from cache");
	}
}
 
Example #21
Source File: TrimouViewResolver.java    From spring-comparing-template-engines with Apache License 2.0 5 votes vote down vote up
@Override
protected View loadView(final String viewName, final Locale locale) throws Exception {
	Mustache mustache = engine.getMustache(viewName);
	if (mustache != null) {
		TrimouView trimouView = (TrimouView) super.loadView(viewName, locale);
		trimouView.setMustache(mustache);

		return trimouView;
	}
	return null;
}
 
Example #22
Source File: DispatcherPortlet.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Actually render the given view.
 * <p>The default implementation delegates to
 * {@link org.springframework.web.servlet.ViewRendererServlet}.
 * @param view the View to render
 * @param model the associated model
 * @param request current portlet render/resource request
 * @param response current portlet render/resource response
 * @throws Exception if there's a problem rendering the view
 */
protected void doRender(View view, Map<String, ?> model, PortletRequest request, MimeResponse response) throws Exception {
	// Expose Portlet ApplicationContext to view objects.
	request.setAttribute(ViewRendererServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, getPortletApplicationContext());

	// These attributes are required by the ViewRendererServlet.
	request.setAttribute(ViewRendererServlet.VIEW_ATTRIBUTE, view);
	request.setAttribute(ViewRendererServlet.MODEL_ATTRIBUTE, model);

	// Include the content of the view in the render/resource response.
	doDispatch(getPortletContext().getRequestDispatcher(this.viewRendererUrl), request, response);
}
 
Example #23
Source File: BaseViewTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void pathVarsOverrideStaticAttributes() throws Exception {
	WebApplicationContext wac = mock(WebApplicationContext.class);
	given(wac.getServletContext()).willReturn(new MockServletContext());

	HttpServletRequest request = new MockHttpServletRequest();
	HttpServletResponse response = new MockHttpServletResponse();

	TestView tv = new TestView(wac);
	tv.setApplicationContext(wac);

	Properties p = new Properties();
	p.setProperty("one", "bar");
	p.setProperty("something", "else");
	tv.setAttributes(p);

	Map<String, Object> pathVars = new HashMap<>();
	pathVars.put("one", new HashMap<>());
	pathVars.put("two", new Object());
	request.setAttribute(View.PATH_VARIABLES, pathVars);

	tv.render(new HashMap<>(), request, response);

	checkContainsAll(pathVars, tv.model);

	assertEquals(3, tv.model.size());
	assertEquals("else", tv.model.get("something"));
	assertTrue(tv.initialized);
}
 
Example #24
Source File: FreeMarkerViewTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void freeMarkerViewResolver() throws Exception {
	FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
	configurer.setConfiguration(new TestConfiguration());

	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	wac.setServletContext(new MockServletContext());
	wac.getBeanFactory().registerSingleton("configurer", configurer);
	wac.refresh();

	FreeMarkerViewResolver vr = new FreeMarkerViewResolver();
	vr.setPrefix("prefix_");
	vr.setSuffix("_suffix");
	vr.setApplicationContext(wac);

	View view = vr.resolveViewName("test", Locale.CANADA);
	assertEquals("Correct view class", FreeMarkerView.class, view.getClass());
	assertEquals("Correct URL", "prefix_test_suffix", ((FreeMarkerView) view).getUrl());

	view = vr.resolveViewName("non-existing", Locale.CANADA);
	assertNull(view);

	view = vr.resolveViewName("redirect:myUrl", Locale.getDefault());
	assertEquals("Correct view class", RedirectView.class, view.getClass());
	assertEquals("Correct URL", "myUrl", ((RedirectView) view).getUrl());

	view = vr.resolveViewName("forward:myUrl", Locale.getDefault());
	assertEquals("Correct view class", InternalResourceView.class, view.getClass());
	assertEquals("Correct URL", "myUrl", ((InternalResourceView) view).getUrl());
}
 
Example #25
Source File: ServletAnnotationControllerHandlerMethodTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public View resolveViewName(final String viewName, Locale locale) throws Exception {
	return new View() {
		@Override
		public String getContentType() {
			return null;
		}
		@Override
		public void render(@Nullable Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) {
			request.setAttribute("viewName", viewName);
			request.getSession().setAttribute("model", model);
		}
	};
}
 
Example #26
Source File: ExtendedThymeleafViewResolver.java    From wallride with Apache License 2.0 5 votes vote down vote up
@Override
protected View createView(final String viewName, final Locale locale) throws Exception {
	View view = super.createView(viewName, locale);
	if (view instanceof RedirectView) {
		RedirectView redirectView = (RedirectView) view;
		redirectView.setApplicationContext(getApplicationContext());
		redirectView.setServletContext(getServletContext());
	}
	return view;
}
 
Example #27
Source File: ViewResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testInternalResourceViewResolverWithJstl() throws Exception {
	Locale locale = !Locale.GERMAN.equals(Locale.getDefault()) ? Locale.GERMAN : Locale.FRENCH;

	MockServletContext sc = new MockServletContext();
	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	wac.setServletContext(sc);
	wac.addMessage("code1", locale, "messageX");
	wac.refresh();
	InternalResourceViewResolver vr = new InternalResourceViewResolver();
	vr.setViewClass(JstlView.class);
	vr.setApplicationContext(wac);

	View view = vr.resolveViewName("example1", Locale.getDefault());
	assertEquals("Correct view class", JstlView.class, view.getClass());
	assertEquals("Correct URL", "example1", ((JstlView) view).getUrl());

	view = vr.resolveViewName("example2", Locale.getDefault());
	assertEquals("Correct view class", JstlView.class, view.getClass());
	assertEquals("Correct URL", "example2", ((JstlView) view).getUrl());

	MockHttpServletRequest request = new MockHttpServletRequest(sc);
	HttpServletResponse response = new MockHttpServletResponse();
	request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
	request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, new FixedLocaleResolver(locale));
	Map<String, Object> model = new HashMap<>();
	TestBean tb = new TestBean();
	model.put("tb", tb);
	view.render(model, request, response);

	assertTrue("Correct tb attribute", tb.equals(request.getAttribute("tb")));
	assertTrue("Correct rc attribute", request.getAttribute("rc") == null);

	assertEquals(locale, Config.get(request, Config.FMT_LOCALE));
	LocalizationContext lc = (LocalizationContext) Config.get(request, Config.FMT_LOCALIZATION_CONTEXT);
	assertEquals("messageX", lc.getResourceBundle().getString("code1"));
}
 
Example #28
Source File: ViewResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testInternalResourceViewResolverWithSpecificContextBeans() throws Exception {
	MockServletContext sc = new MockServletContext();
	final StaticWebApplicationContext wac = new StaticWebApplicationContext();
	wac.registerSingleton("myBean", TestBean.class);
	wac.registerSingleton("myBean2", TestBean.class);
	wac.setServletContext(sc);
	wac.refresh();
	InternalResourceViewResolver vr = new InternalResourceViewResolver();
	Properties props = new Properties();
	props.setProperty("key1", "value1");
	vr.setAttributes(props);
	Map<String, Object> map = new HashMap<>();
	map.put("key2", new Integer(2));
	vr.setAttributesMap(map);
	vr.setExposedContextBeanNames(new String[] {"myBean2"});
	vr.setApplicationContext(wac);

	MockHttpServletRequest request = new MockHttpServletRequest(sc) {
		@Override
		public RequestDispatcher getRequestDispatcher(String path) {
			return new MockRequestDispatcher(path) {
				@Override
				public void forward(ServletRequest forwardRequest, ServletResponse forwardResponse) {
					assertTrue("Correct rc attribute", forwardRequest.getAttribute("rc") == null);
					assertEquals("value1", forwardRequest.getAttribute("key1"));
					assertEquals(new Integer(2), forwardRequest.getAttribute("key2"));
					assertNull(forwardRequest.getAttribute("myBean"));
					assertSame(wac.getBean("myBean2"), forwardRequest.getAttribute("myBean2"));
				}
			};
		}
	};
	HttpServletResponse response = new MockHttpServletResponse();
	request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
	request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, new AcceptHeaderLocaleResolver());
	View view = vr.resolveViewName("example1", Locale.getDefault());
	view.render(new HashMap<String, Object>(), request, response);
}
 
Example #29
Source File: ThymeleafRender.java    From Aooms with Apache License 2.0 5 votes vote down vote up
@Override
public void render(HttpServletResponse response, Object value) throws  Exception{
    // get ApplicationContext
    ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(AoomsContext.getRequest().getServletContext());

    // get ThymeleafViewResolver Bean
    ThymeleafViewResolver resolver = (ThymeleafViewResolver) ac1.getBean("thymeleafViewResolver");
    View view = resolver.resolveViewName(mv.getViewName(), AoomsContext.getRequest().getLocale());
    view.render(mv.getModel(), AoomsContext.getRequest(), AoomsContext.getResponse());
}
 
Example #30
Source File: ViewResolverTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testInternalResourceViewResolverWithJstlAndContextParam() throws Exception {
	Locale locale = !Locale.GERMAN.equals(Locale.getDefault()) ? Locale.GERMAN : Locale.FRENCH;

	MockServletContext sc = new MockServletContext();
	sc.addInitParameter(Config.FMT_LOCALIZATION_CONTEXT, "org/springframework/web/context/WEB-INF/context-messages");
	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	wac.setServletContext(sc);
	wac.addMessage("code1", locale, "messageX");
	wac.refresh();
	InternalResourceViewResolver vr = new InternalResourceViewResolver();
	vr.setViewClass(JstlView.class);
	vr.setApplicationContext(wac);

	View view = vr.resolveViewName("example1", Locale.getDefault());
	assertEquals("Correct view class", JstlView.class, view.getClass());
	assertEquals("Correct URL", "example1", ((JstlView) view).getUrl());

	view = vr.resolveViewName("example2", Locale.getDefault());
	assertEquals("Correct view class", JstlView.class, view.getClass());
	assertEquals("Correct URL", "example2", ((JstlView) view).getUrl());

	MockHttpServletRequest request = new MockHttpServletRequest(sc);
	HttpServletResponse response = new MockHttpServletResponse();
	request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
	request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, new FixedLocaleResolver(locale));
	Map model = new HashMap();
	TestBean tb = new TestBean();
	model.put("tb", tb);
	view.render(model, request, response);

	assertTrue("Correct tb attribute", tb.equals(request.getAttribute("tb")));
	assertTrue("Correct rc attribute", request.getAttribute("rc") == null);

	assertEquals(locale, Config.get(request, Config.FMT_LOCALE));
	LocalizationContext lc = (LocalizationContext) Config.get(request, Config.FMT_LOCALIZATION_CONTEXT);
	assertEquals("message1", lc.getResourceBundle().getString("code1"));
	assertEquals("message2", lc.getResourceBundle().getString("code2"));
}