Java Code Examples for org.springframework.web.servlet.View

The following examples show how to use org.springframework.web.servlet.View. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@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 2
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
@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 4
@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 5
@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 6
@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 7
@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 8
@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 9
Source Project: spring4-understanding   Source File: ViewResolverTests.java    License: 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 10
@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 11
Source Project: forum   Source File: ProfileController.java    License: 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 12
@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 13
@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 14
@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 15
@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 16
@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 17
Source Project: catnap   Source File: CatnapViewResolver.java    License: 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 18
@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 19
@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 20
Source Project: spring4-understanding   Source File: ViewResolverTests.java    License: 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 21
Source Project: MaxKey   Source File: AuthorizationEndpoint.java    License: Apache License 2.0 5 votes vote down vote up
private View getAuthorizationCodeResponse(AuthorizationRequest authorizationRequest, Authentication authUser) {
	try {
		return new RedirectView(getSuccessfulRedirect(authorizationRequest,
				generateCode(authorizationRequest, authUser)), false, true, false);
	}
	catch (OAuth2Exception e) {
		return new RedirectView(getUnsuccessfulRedirect(authorizationRequest, e, false), false, true, false);
	}
}
 
Example 22
@Test
public void resolveViewNameFilenameDefaultView() throws Exception {
	request.setRequestURI("/test.json");

	Map<String, MediaType> mapping = Collections.singletonMap("json", MediaType.APPLICATION_JSON);
	PathExtensionContentNegotiationStrategy pathStrategy = new PathExtensionContentNegotiationStrategy(mapping);
	viewResolver.setContentNegotiationManager(new ContentNegotiationManager(pathStrategy));

	ViewResolver viewResolverMock1 = mock(ViewResolver.class);
	ViewResolver viewResolverMock2 = mock(ViewResolver.class);
	viewResolver.setViewResolvers(Arrays.asList(viewResolverMock1, viewResolverMock2));

	View viewMock1 = mock(View.class, "application_xml");
	View viewMock2 = mock(View.class, "text_html");
	View viewMock3 = mock(View.class, "application_json");

	List<View> defaultViews = new ArrayList<View>();
	defaultViews.add(viewMock3);
	viewResolver.setDefaultViews(defaultViews);

	viewResolver.afterPropertiesSet();

	String viewName = "view";
	Locale locale = Locale.ENGLISH;

	given(viewResolverMock1.resolveViewName(viewName, locale)).willReturn(viewMock1);
	given(viewResolverMock1.resolveViewName(viewName + ".json", locale)).willReturn(null);
	given(viewResolverMock2.resolveViewName(viewName, locale)).willReturn(viewMock2);
	given(viewResolverMock2.resolveViewName(viewName + ".json", locale)).willReturn(null);
	given(viewMock1.getContentType()).willReturn("application/xml");
	given(viewMock2.getContentType()).willReturn("text/html;charset=ISO-8859-1");
	given(viewMock3.getContentType()).willReturn("application/json");

	View result = viewResolver.resolveViewName(viewName, locale);
	assertSame("Invalid view", viewMock3, result);
}
 
Example 23
Source Project: spring4-understanding   Source File: RedirectViewTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void attributeStatusCodeHttp10() throws Exception {
	RedirectView rv = new RedirectView();
	rv.setUrl("http://url.somewhere.com");
	MockHttpServletRequest request = createRequest();
	request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.CREATED);
	MockHttpServletResponse response = new MockHttpServletResponse();
	rv.render(new HashMap<String, Object>(), request, response);
	assertEquals(201, response.getStatus());
	assertEquals("http://url.somewhere.com", response.getHeader("Location"));
}
 
Example 24
Source Project: rqueue   Source File: RqueueViewController.java    License: Apache License 2.0 5 votes vote down vote up
@GetMapping("scheduled")
public View scheduled(Model model, HttpServletResponse response) throws Exception {
  if (!rqueueWebConfig.isEnable()) {
    response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
    return null;
  }
  addBasicDetails(model);
  addNavData(model, NavTab.SCHEDULED);
  model.addAttribute("title", "Scheduled Tasks");
  List<List<Object>> l = rqueueQDetailService.getScheduledTasks();
  model.addAttribute("tasks", l.subList(1, l.size()));
  model.addAttribute("header", l.get(0));
  return rqueueViewResolver.resolveViewName("running", Locale.ENGLISH);
}
 
Example 25
/**
 * Return a ModelAndView object with the specified view name.
 * <p>The content of the {@link RequestContextUtils#getInputFlashMap
 * "input" FlashMap} is also added to the model.
 * @see #getViewName()
 */
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
		throws Exception {

	String viewName = getViewName();

	if (getStatusCode() != null) {
		if (getStatusCode().is3xxRedirection()) {
			request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, getStatusCode());
		}
		else {
			response.setStatus(getStatusCode().value());
			if (getStatusCode().equals(HttpStatus.NO_CONTENT) && viewName == null) {
				return null;
			}
		}
	}

	if (isStatusOnly()) {
		return null;
	}

	ModelAndView modelAndView = new ModelAndView();
	modelAndView.addAllObjects(RequestContextUtils.getInputFlashMap(request));
	if (viewName != null) {
		modelAndView.setViewName(viewName);
	}
	else {
		modelAndView.setView(getView());
	}
	return modelAndView;
}
 
Example 26
Source Project: spring-analysis-note   Source File: AbstractCachingViewResolver.java    License: MIT License 5 votes vote down vote up
@Override
@Nullable
public View resolveViewName(String viewName, Locale locale) throws Exception {
	if (!isCache()) {
		return createView(viewName, locale);
	}
	else {
		Object cacheKey = getCacheKey(viewName, locale);
		View view = this.viewAccessCache.get(cacheKey);
		if (view == null) {
			synchronized (this.viewCreationCache) {
				view = this.viewCreationCache.get(cacheKey);
				if (view == null) {
					// Ask the subclass to create the View object.
					view = createView(viewName, locale);
					if (view == null && this.cacheUnresolved) {
						view = UNRESOLVED_VIEW;
					}
					if (view != null) {
						this.viewAccessCache.put(cacheKey, view);
						this.viewCreationCache.put(cacheKey, view);
					}
				}
			}
		}
		else {
			if (logger.isTraceEnabled()) {
				logger.trace(formatKey(cacheKey) + "served from cache");
			}
		}
		return (view != UNRESOLVED_VIEW ? view : null);
	}
}
 
Example 27
Source Project: onetwo   Source File: MvcViewRender.java    License: Apache License 2.0 5 votes vote down vote up
protected View resolveViewName(String viewName, Map<String, Object> model, Locale locale,
		HttpServletRequest request) throws Exception {

	for (ViewResolver viewResolver : this.viewResolvers) {
		View view = viewResolver.resolveViewName(viewName, locale);
		if (view != null) {
			return view;
		}
	}
	return null;
}
 
Example 28
Source Project: spring-analysis-note   Source File: RedirectView.java    License: MIT License 5 votes vote down vote up
/**
 * Determines the status code to use for HTTP 1.1 compatible requests.
 * <p>The default implementation returns the {@link #setStatusCode(HttpStatus) statusCode}
 * property if set, or the value of the {@link #RESPONSE_STATUS_ATTRIBUTE} attribute.
 * If neither are set, it defaults to {@link HttpStatus#SEE_OTHER} (303).
 * @param request the request to inspect
 * @param response the servlet response
 * @param targetUrl the target URL
 * @return the response status
 */
protected HttpStatus getHttp11StatusCode(
		HttpServletRequest request, HttpServletResponse response, String targetUrl) {

	if (this.statusCode != null) {
		return this.statusCode;
	}
	HttpStatus attributeStatusCode = (HttpStatus) request.getAttribute(View.RESPONSE_STATUS_ATTRIBUTE);
	if (attributeStatusCode != null) {
		return attributeStatusCode;
	}
	return HttpStatus.SEE_OTHER;
}
 
Example 29
@Override
@Nullable
public View resolveViewName(String viewName, Locale locale) throws Exception {
	RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
	Assert.state(attrs instanceof ServletRequestAttributes, "No current ServletRequestAttributes");
	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;
		}
	}

	String mediaTypeInfo = logger.isDebugEnabled() && requestedMediaTypes != null ?
			" given " + requestedMediaTypes.toString() : "";

	if (this.useNotAcceptableStatusCode) {
		if (logger.isDebugEnabled()) {
			logger.debug("Using 406 NOT_ACCEPTABLE" + mediaTypeInfo);
		}
		return NOT_ACCEPTABLE_VIEW;
	}
	else {
		logger.debug("View remains unresolved" + mediaTypeInfo);
		return null;
	}
}
 
Example 30
Source Project: cxf   Source File: SpringViewResolverProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIsWriteableEnum() throws Exception {
    String viewName = "/test";
    View view = expectGetView(viewName);
    viewResolver.setClassResources(Collections.singletonMap(TestEnum.class.getName() + "."
            + TestEnum.ONE, viewName));
    replayAll();
    assertTrue(viewResolver.isWriteable(TestEnum.ONE.getClass(), null, null, null));
    assertEquals(view, viewResolver.getView(TestEnum.ONE.getClass(), TestEnum.ONE));
}