org.springframework.web.util.WebUtils Java Examples

The following examples show how to use org.springframework.web.util.WebUtils. 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: CharacterEncodingFilterTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void setForceEncodingOnRequestOnly() throws Exception {
	HttpServletRequest request = mock(HttpServletRequest.class);
	request.setCharacterEncoding(ENCODING);
	given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null);
	given(request.getAttribute(filteredName(FILTER_NAME))).willReturn(null);

	HttpServletResponse response = mock(HttpServletResponse.class);
	FilterChain filterChain = mock(FilterChain.class);

	CharacterEncodingFilter filter = new CharacterEncodingFilter(ENCODING, true, false);
	filter.init(new MockFilterConfig(FILTER_NAME));
	filter.doFilter(request, response, filterChain);

	verify(request).setAttribute(filteredName(FILTER_NAME), Boolean.TRUE);
	verify(request).removeAttribute(filteredName(FILTER_NAME));
	verify(request, times(2)).setCharacterEncoding(ENCODING);
	verify(response, never()).setCharacterEncoding(ENCODING);
	verify(filterChain).doFilter(request, response);
}
 
Example #2
Source File: CookieLocaleResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testResolveLocaleContextWithInvalidLocaleOnErrorDispatch() {
	MockHttpServletRequest request = new MockHttpServletRequest();
	request.addPreferredLocale(Locale.GERMAN);
	request.setAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE, new ServletException());
	Cookie cookie = new Cookie("LanguageKoekje", "++ GMT+1");
	request.setCookies(cookie);

	CookieLocaleResolver resolver = new CookieLocaleResolver();
	resolver.setDefaultTimeZone(TimeZone.getTimeZone("GMT+2"));
	resolver.setCookieName("LanguageKoekje");
	LocaleContext loc = resolver.resolveLocaleContext(request);
	assertEquals(Locale.GERMAN, loc.getLocale());
	assertTrue(loc instanceof TimeZoneAwareLocaleContext);
	assertEquals(TimeZone.getTimeZone("GMT+2"), ((TimeZoneAwareLocaleContext) loc).getTimeZone());
}
 
Example #3
Source File: RedisSecurityContextRepository.java    From onetwo with Apache License 2.0 6 votes vote down vote up
@Override
public void saveContext(SecurityContext context, HttpServletRequest request, HttpServletResponse response) {
	SaveToSessionResponseWrapper responseWrapper = WebUtils.getNativeResponse(response, SaveToSessionResponseWrapper.class);
	if (responseWrapper == null) {
		throw new IllegalStateException(
				"Cannot invoke saveContext on response "
						+ response
						+ ". You must use the HttpRequestResponseHolder.response after invoking loadContext");
	}
	// saveContext() might already be called by the response wrapper
	// if something in the chain called sendError() or sendRedirect(). This ensures we
	// only call it
	// once per request.
	if (!responseWrapper.isContextSaved()) {
		responseWrapper.saveContext(context);
	}
}
 
Example #4
Source File: AbstractSockJsService.java    From spring-analysis-note with MIT License 6 votes vote down vote up
protected boolean checkOrigin(ServerHttpRequest request, ServerHttpResponse response, HttpMethod... httpMethods)
		throws IOException {

	if (WebUtils.isSameOrigin(request)) {
		return true;
	}

	if (!WebUtils.isValidOrigin(request, this.allowedOrigins)) {
		if (logger.isWarnEnabled()) {
			logger.warn("Origin header value '" + request.getHeaders().getOrigin() + "' not allowed.");
		}
		response.setStatusCode(HttpStatus.FORBIDDEN);
		return false;
	}

	return true;
}
 
Example #5
Source File: DispatcherServletTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void cleanupAfterIncludeWithRemove() throws ServletException, IOException {
	MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/main.do");
	MockHttpServletResponse response = new MockHttpServletResponse();

	request.setAttribute("test1", "value1");
	request.setAttribute("test2", "value2");
	WebApplicationContext wac = new StaticWebApplicationContext();
	request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);

	request.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, "/form.do");
	simpleDispatcherServlet.service(request, response);

	assertEquals("value1", request.getAttribute("test1"));
	assertEquals("value2", request.getAttribute("test2"));
	assertEquals(wac, request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE));
	assertNull(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE));
	assertNull(request.getAttribute("command"));
}
 
Example #6
Source File: CookieThemeResolver.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public String resolveThemeName(HttpServletRequest request) {
	// Check request for preparsed or preset theme.
	String themeName = (String) request.getAttribute(THEME_REQUEST_ATTRIBUTE_NAME);
	if (themeName != null) {
		return themeName;
	}

	// Retrieve cookie value from request.
	Cookie cookie = WebUtils.getCookie(request, getCookieName());
	if (cookie != null) {
		String value = cookie.getValue();
		if (StringUtils.hasText(value)) {
			themeName = value;
		}
	}

	// Fall back to default theme.
	if (themeName == null) {
		themeName = getDefaultThemeName();
	}
	request.setAttribute(THEME_REQUEST_ATTRIBUTE_NAME, themeName);
	return themeName;
}
 
Example #7
Source File: AuthenticationController.java    From computoser with GNU Affero General Public License v3.0 6 votes vote down vote up
@RequestMapping("/logout")
public String logout(HttpSession session, HttpServletRequest request, HttpServletResponse response) {
    session.invalidate();
    Cookie cookie = WebUtils.getCookie(request, SocialSignInAdapter.AUTH_TOKEN_COOKIE_NAME);
    if (cookie != null) {
        cookie.setMaxAge(0);
        cookie.setDomain(".computoser.com");
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    cookie = WebUtils.getCookie(request, SocialSignInAdapter.AUTH_TOKEN_SERIES_COOKIE_NAME);
    if (cookie != null) {
        cookie.setMaxAge(0);
        cookie.setDomain(".computoser.com");
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    return "redirect:/";
}
 
Example #8
Source File: HtmlEscapeTagTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void htmlEscapeTagWithContextParamFalse() throws JspException {
	PageContext pc = createPageContext();
	MockServletContext sc = (MockServletContext) pc.getServletContext();
	HtmlEscapeTag tag = new HtmlEscapeTag();
	tag.setPageContext(pc);
	tag.doStartTag();

	sc.addInitParameter(WebUtils.HTML_ESCAPE_CONTEXT_PARAM, "false");
	assertTrue("Correct default", !tag.getRequestContext().isDefaultHtmlEscape());
	tag.setDefaultHtmlEscape(true);
	assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
	assertTrue("Correctly enabled", tag.getRequestContext().isDefaultHtmlEscape());
	tag.setDefaultHtmlEscape(false);
	assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
	assertTrue("Correctly disabled", !tag.getRequestContext().isDefaultHtmlEscape());
}
 
Example #9
Source File: SessionLocaleResolver.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
public LocaleContext resolveLocaleContext(final HttpServletRequest request) {
	return new TimeZoneAwareLocaleContext() {
		@Override
		public Locale getLocale() {
			Locale locale = (Locale) WebUtils.getSessionAttribute(request, localeAttributeName);
			if (locale == null) {
				locale = determineDefaultLocale(request);
			}
			return locale;
		}
		@Override
		@Nullable
		public TimeZone getTimeZone() {
			TimeZone timeZone = (TimeZone) WebUtils.getSessionAttribute(request, timeZoneAttributeName);
			if (timeZone == null) {
				timeZone = determineDefaultTimeZone(request);
			}
			return timeZone;
		}
	};
}
 
Example #10
Source File: DispatcherServletTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void noCleanupAfterInclude() throws ServletException, IOException {
	MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", "/main.do");
	MockHttpServletResponse response = new MockHttpServletResponse();

	request.setAttribute("test1", "value1");
	request.setAttribute("test2", "value2");
	WebApplicationContext wac = new StaticWebApplicationContext();
	request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
	TestBean command = new TestBean();
	request.setAttribute("command", command);

	request.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, "/form.do");
	simpleDispatcherServlet.setCleanupAfterInclude(false);
	simpleDispatcherServlet.service(request, response);

	assertEquals("value1", request.getAttribute("test1"));
	assertEquals("value2", request.getAttribute("test2"));
	assertSame(wac, request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE));
}
 
Example #11
Source File: CharacterEncodingFilterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void encodingIfEmptyAndNotForced() throws Exception {
	HttpServletRequest request = mock(HttpServletRequest.class);
	given(request.getCharacterEncoding()).willReturn(null);
	given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null);
	given(request.getAttribute(filteredName(FILTER_NAME))).willReturn(null);

	MockHttpServletResponse response = new MockHttpServletResponse();

	FilterChain filterChain = mock(FilterChain.class);

	CharacterEncodingFilter filter = new CharacterEncodingFilter(ENCODING);
	filter.init(new MockFilterConfig(FILTER_NAME));
	filter.doFilter(request, response, filterChain);

	verify(request).setCharacterEncoding(ENCODING);
	verify(request).setAttribute(filteredName(FILTER_NAME), Boolean.TRUE);
	verify(request).removeAttribute(filteredName(FILTER_NAME));
	verify(filterChain).doFilter(request, response);
}
 
Example #12
Source File: CharacterEncodingFilterTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void withIncompleteInitialization() throws Exception {
	HttpServletRequest request = mock(HttpServletRequest.class);
	given(request.getCharacterEncoding()).willReturn(null);
	given(request.getAttribute(WebUtils.ERROR_REQUEST_URI_ATTRIBUTE)).willReturn(null);
	given(request.getAttribute(filteredName(CharacterEncodingFilter.class.getName()))).willReturn(null);

	MockHttpServletResponse response = new MockHttpServletResponse();

	FilterChain filterChain = mock(FilterChain.class);

	CharacterEncodingFilter filter = new CharacterEncodingFilter(ENCODING);
	filter.doFilter(request, response, filterChain);

	verify(request).setCharacterEncoding(ENCODING);
	verify(request).setAttribute(filteredName(CharacterEncodingFilter.class.getName()), Boolean.TRUE);
	verify(request).removeAttribute(filteredName(CharacterEncodingFilter.class.getName()));
	verify(filterChain).doFilter(request, response);
}
 
Example #13
Source File: FlashMapManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test // SPR-15505
public void retrieveAndUpdateMatchByOriginatingPathAndQueryString() {
	FlashMap flashMap = new FlashMap();
	flashMap.put("key", "value");
	flashMap.setTargetRequestPath("/accounts");
	flashMap.addTargetRequestParam("a", "b");

	this.flashMapManager.setFlashMaps(Collections.singletonList(flashMap));

	this.request.setAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE, "/accounts");
	this.request.setAttribute(WebUtils.FORWARD_QUERY_STRING_ATTRIBUTE, "a=b");
	this.request.setRequestURI("/mvc/accounts");
	this.request.setQueryString("x=y");
	FlashMap inputFlashMap = this.flashMapManager.retrieveAndUpdate(this.request, this.response);

	assertEquals(flashMap, inputFlashMap);
	assertEquals("Input FlashMap should have been removed", 0, this.flashMapManager.getFlashMaps().size());
}
 
Example #14
Source File: AbstractController.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
		throws Exception {

	// Delegate to WebContentGenerator for checking and preparing.
	checkRequest(request);
	prepareResponse(response);

	// Execute handleRequestInternal in synchronized block if required.
	if (this.synchronizeOnSession) {
		HttpSession session = request.getSession(false);
		if (session != null) {
			Object mutex = WebUtils.getSessionMutex(session);
			synchronized (mutex) {
				return handleRequestInternal(request, response);
			}
		}
	}

	return handleRequestInternal(request, response);
}
 
Example #15
Source File: SurveyDefinitionController.java    From JDeSurvey with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Encodes a string path suing the  httpServletRequest Character Encoding
 * @param pathSegment
 * @param httpServletRequest
 * @return
 */
String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
	log.info("encodeUrlPathSegment()");
	try{
		String enc = httpServletRequest.getCharacterEncoding();
		if (enc == null) {
			enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
		}
		try {
			pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
		} catch (UnsupportedEncodingException uee) {log.error(uee);}
		return pathSegment;
	} catch (Exception e) {
		log.error(e.getMessage(),e);
		throw (new RuntimeException(e));
	}
}
 
Example #16
Source File: XsltView.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Configure the supplied {@link HttpServletResponse}.
 * <p>The default implementation of this method sets the
 * {@link HttpServletResponse#setContentType content type} and
 * {@link HttpServletResponse#setCharacterEncoding encoding}
 * from the "media-type" and "encoding" output properties
 * specified in the {@link Transformer}.
 * @param model merged output Map (never {@code null})
 * @param response current HTTP response
 * @param transformer the target transformer
 */
protected void configureResponse(Map<String, Object> model, HttpServletResponse response, Transformer transformer) {
	String contentType = getContentType();
	String mediaType = transformer.getOutputProperty(OutputKeys.MEDIA_TYPE);
	String encoding = transformer.getOutputProperty(OutputKeys.ENCODING);
	if (StringUtils.hasText(mediaType)) {
		contentType = mediaType;
	}
	if (StringUtils.hasText(encoding)) {
		// Only apply encoding if content type is specified but does not contain charset clause already.
		if (contentType != null && !contentType.toLowerCase().contains(WebUtils.CONTENT_TYPE_CHARSET_PREFIX)) {
			contentType = contentType + WebUtils.CONTENT_TYPE_CHARSET_PREFIX + encoding;
		}
	}
	response.setContentType(contentType);
}
 
Example #17
Source File: ViewCartController.java    From jpetstore-kubernetes with Apache License 2.0 6 votes vote down vote up
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
	UserSession userSession = (UserSession) WebUtils.getSessionAttribute(request, "userSession");
	Cart cart = (Cart) WebUtils.getOrCreateSessionAttribute(request.getSession(), "sessionCart", Cart.class);
	String page = request.getParameter("page");
	if (userSession != null) {
		if ("next".equals(page)) {
			userSession.getMyList().nextPage();
		}
		else if ("previous".equals(page)) {
			userSession.getMyList().previousPage();
		}
	}
	if ("nextCart".equals(page)) {
		cart.getCartItemList().nextPage();
	}
	else if ("previousCart".equals(page)) {
		cart.getCartItemList().previousPage();
	}
	return new ModelAndView(this.successView, "cart", cart);
}
 
Example #18
Source File: HtmlEscapeTagTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void htmlEscapeTagWithContextParamTrue() throws JspException {
	PageContext pc = createPageContext();
	MockServletContext sc = (MockServletContext) pc.getServletContext();
	sc.addInitParameter(WebUtils.HTML_ESCAPE_CONTEXT_PARAM, "true");
	HtmlEscapeTag tag = new HtmlEscapeTag();
	tag.setDefaultHtmlEscape(false);
	tag.setPageContext(pc);
	tag.doStartTag();

	assertTrue("Correct default", !tag.getRequestContext().isDefaultHtmlEscape());
	tag.setDefaultHtmlEscape(true);
	assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
	assertTrue("Correctly enabled", tag.getRequestContext().isDefaultHtmlEscape());
	tag.setDefaultHtmlEscape(false);
	assertTrue("Correct doStartTag return value", tag.doStartTag() == Tag.EVAL_BODY_INCLUDE);
	assertTrue("Correctly disabled", !tag.getRequestContext().isDefaultHtmlEscape());
}
 
Example #19
Source File: RequestMappingInfoHandlerMapping.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private Map<String, MultiValueMap<String, String>> extractMatrixVariables(
		HttpServletRequest request, Map<String, String> uriVariables) {

	Map<String, MultiValueMap<String, String>> result = new LinkedHashMap<String, MultiValueMap<String, String>>();
	for (Entry<String, String> uriVar : uriVariables.entrySet()) {
		String uriVarValue = uriVar.getValue();

		int equalsIndex = uriVarValue.indexOf('=');
		if (equalsIndex == -1) {
			continue;
		}

		String matrixVariables;

		int semicolonIndex = uriVarValue.indexOf(';');
		if ((semicolonIndex == -1) || (semicolonIndex == 0) || (equalsIndex < semicolonIndex)) {
			matrixVariables = uriVarValue;
		}
		else {
			matrixVariables = uriVarValue.substring(semicolonIndex + 1);
			uriVariables.put(uriVar.getKey(), uriVarValue.substring(0, semicolonIndex));
		}

		MultiValueMap<String, String> vars = WebUtils.parseMatrixVariables(matrixVariables);
		result.put(uriVar.getKey(), getUrlPathHelper().decodeMatrixVariables(request, vars));
	}
	return result;
}
 
Example #20
Source File: CommonsMultipartResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void withServletContextAndFilter() throws Exception {
	StaticWebApplicationContext wac = new StaticWebApplicationContext();
	wac.setServletContext(new MockServletContext());
	wac.registerSingleton("filterMultipartResolver", MockCommonsMultipartResolver.class, new MutablePropertyValues());
	wac.getServletContext().setAttribute(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, new File("mytemp"));
	wac.refresh();
	wac.getServletContext().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
	CommonsMultipartResolver resolver = new CommonsMultipartResolver(wac.getServletContext());
	assertTrue(resolver.getFileItemFactory().getRepository().getAbsolutePath().endsWith("mytemp"));

	MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter");
	filterConfig.addInitParameter("class", "notWritable");
	filterConfig.addInitParameter("unknownParam", "someValue");
	final MultipartFilter filter = new MultipartFilter();
	filter.init(filterConfig);

	final List<MultipartFile> files = new ArrayList<>();
	final FilterChain filterChain = new FilterChain() {
		@Override
		public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) {
			MultipartHttpServletRequest request = (MultipartHttpServletRequest) servletRequest;
			files.addAll(request.getFileMap().values());
		}
	};

	FilterChain filterChain2 = new PassThroughFilterChain(filter, filterChain);

	MockHttpServletRequest originalRequest = new MockHttpServletRequest();
	MockHttpServletResponse response = new MockHttpServletResponse();
	originalRequest.setMethod("POST");
	originalRequest.setContentType("multipart/form-data");
	originalRequest.addHeader("Content-type", "multipart/form-data");
	filter.doFilter(originalRequest, response, filterChain2);

	CommonsMultipartFile file1 = (CommonsMultipartFile) files.get(0);
	CommonsMultipartFile file2 = (CommonsMultipartFile) files.get(1);
	assertTrue(((MockFileItem) file1.getFileItem()).deleted);
	assertTrue(((MockFileItem) file2.getFileItem()).deleted);
}
 
Example #21
Source File: ShallowEtagHeaderFilter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private void updateResponse(HttpServletRequest request, HttpServletResponse response) throws IOException {
	ContentCachingResponseWrapper responseWrapper =
			WebUtils.getNativeResponse(response, ContentCachingResponseWrapper.class);
	Assert.notNull(responseWrapper, "ContentCachingResponseWrapper not found");
	HttpServletResponse rawResponse = (HttpServletResponse) responseWrapper.getResponse();
	int statusCode = responseWrapper.getStatusCode();

	if (rawResponse.isCommitted()) {
		responseWrapper.copyBodyToResponse();
	}
	else if (isEligibleForEtag(request, responseWrapper, statusCode, responseWrapper.getContentInputStream())) {
		String responseETag = generateETagHeaderValue(responseWrapper.getContentInputStream());
		rawResponse.setHeader(HEADER_ETAG, responseETag);
		String requestETag = request.getHeader(HEADER_IF_NONE_MATCH);
		if (responseETag.equals(requestETag)) {
			if (logger.isTraceEnabled()) {
				logger.trace("ETag [" + responseETag + "] equal to If-None-Match, sending 304");
			}
			rawResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
		}
		else {
			if (logger.isTraceEnabled()) {
				logger.trace("ETag [" + responseETag + "] not equal to If-None-Match [" + requestETag +
						"], sending normal response");
			}
			responseWrapper.copyBodyToResponse();
		}
	}
	else {
		if (logger.isTraceEnabled()) {
			logger.trace("Response with status code [" + statusCode + "] not eligible for ETag");
		}
		responseWrapper.copyBodyToResponse();
	}
}
 
Example #22
Source File: CookieThemeResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public String resolveThemeName(HttpServletRequest request) {
	// Check request for preparsed or preset theme.
	String themeName = (String) request.getAttribute(THEME_REQUEST_ATTRIBUTE_NAME);
	if (themeName != null) {
		return themeName;
	}

	// Retrieve cookie value from request.
	String cookieName = getCookieName();
	if (cookieName != null) {
		Cookie cookie = WebUtils.getCookie(request, cookieName);
		if (cookie != null) {
			String value = cookie.getValue();
			if (StringUtils.hasText(value)) {
				themeName = value;
			}
		}
	}

	// Fall back to default theme.
	if (themeName == null) {
		themeName = getDefaultThemeName();
	}
	request.setAttribute(THEME_REQUEST_ATTRIBUTE_NAME, themeName);
	return themeName;
}
 
Example #23
Source File: LogonUtils.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
public static LogonStateBundle getBundle(HttpServletRequest request, boolean create) {
    Object object = WebUtils.getSessionAttribute(request, BUNDLE_KEY);

    if (object instanceof LogonStateBundle) {
        return (LogonStateBundle) object;
    }

    if (create) {
        LogonStateBundle bundle = new LogonStateBundle(LogonState.PENDING);
        WebUtils.setSessionAttribute(request, BUNDLE_KEY, bundle);
        return bundle;
    }

    return null;
}
 
Example #24
Source File: SimpleMappingExceptionResolverTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void noDefaultStatusCodeInInclude() {
	exceptionResolver.setDefaultErrorView("default-view");
	exceptionResolver.setDefaultStatusCode(HttpServletResponse.SC_BAD_REQUEST);
	request.setAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE, "some path");
	exceptionResolver.resolveException(request, response, handler1, genericException);
	assertEquals(HttpServletResponse.SC_OK, response.getStatus());
}
 
Example #25
Source File: UserRestControllerTest.java    From jeecg with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreate() throws Exception {
	//整理请求参数
	HashMap<String, String> map = new HashMap<String, String>();
	map.put("mobilePhone", "mobilePhone");
	map.put("officePhone", "officePhone");
	map.put("email", "email");
	map.put("createBy", ((Client)session.getAttribute(session.getId())).getUser().getId());
	map.put("createName", ((Client)session.getAttribute(session.getId())).getUser().getUserName());
	map.put("updateBy", ((Client)session.getAttribute(session.getId())).getUser().getId());
	map.put("updateName", ((Client)session.getAttribute(session.getId())).getUser().getUserName());
	map.put("devFlag", "1");
	map.put("mobilePhone", "mobilePhone");
	map.put("realName", "realName");
	map.put("status", Globals.User_Normal+"");
	map.put("activitiSync", "1");
	map.put("userName", "testRestMockMvc");
	map.put("password", PasswordUtil.encrypt("testRestMockMvc", "123456", PasswordUtil.getStaticSalt()));
	//发送请求
	this.mockMvc.perform(MockMvcRequestBuilders.post("/rest/user")
			.requestAttr(WebUtils.INCLUDE_SERVLET_PATH_ATTRIBUTE, "/rest")
			.content(StringUtil.HashMapToJsonContent(map))
			.contentType(MediaType.APPLICATION_JSON)
			.characterEncoding("UTF-8")
			.header("USER-AGENT", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36")  // 设置USER-AGENT: 浏览器 
			.session(session))
			.andDo(print())
			//实际未成功,@Transactional自动回滚
			.andExpect(status().is(HttpStatus.CREATED.value()))
			.andReturn();
}
 
Example #26
Source File: PathExtensionContentNegotiationStrategy.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected String getMediaTypeKey(NativeWebRequest webRequest) {
	HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
	if (request == null) {
		logger.warn("An HttpServletRequest is required to determine the media type key");
		return null;
	}
	String path = PATH_HELPER.getLookupPathForRequest(request);
	String filename = WebUtils.extractFullFilenameFromUrlPath(path);
	String extension = StringUtils.getFilenameExtension(filename);
	return (StringUtils.hasText(extension)) ? extension.toLowerCase(Locale.ENGLISH) : null;
}
 
Example #27
Source File: RedirectViewTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
	this.request = new MockHttpServletRequest();
	this.request.setContextPath("/context");
	this.request.setCharacterEncoding(WebUtils.DEFAULT_CHARACTER_ENCODING);
	this.request.setAttribute(DispatcherServlet.OUTPUT_FLASH_MAP_ATTRIBUTE, new FlashMap());
	this.request.setAttribute(DispatcherServlet.FLASH_MAP_MANAGER_ATTRIBUTE, new SessionFlashMapManager());
	this.response = new MockHttpServletResponse();

}
 
Example #28
Source File: MockServletContext.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Create a new {@code MockServletContext} using the supplied resource base
 * path and resource loader.
 * <p>Registers a {@link MockRequestDispatcher} for the Servlet named
 * {@literal 'default'}.
 * @param resourceBasePath the root directory of the WAR (should not end with a slash)
 * @param resourceLoader the ResourceLoader to use (or null for the default)
 * @see #registerNamedDispatcher
 */
public MockServletContext(String resourceBasePath, @Nullable ResourceLoader resourceLoader) {
	this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader());
	this.resourceBasePath = resourceBasePath;

	// Use JVM temp dir as ServletContext temp dir.
	String tempDir = System.getProperty(TEMP_DIR_SYSTEM_PROPERTY);
	if (tempDir != null) {
		this.attributes.put(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, new File(tempDir));
	}

	registerNamedDispatcher(this.defaultServletName, new MockRequestDispatcher(this.defaultServletName));
}
 
Example #29
Source File: CookieCsrfTokenRepository.java    From xmanager with Apache License 2.0 5 votes vote down vote up
@Override
public CsrfTokenBean loadToken(HttpServletRequest request) {
	Cookie cookie = WebUtils.getCookie(request, this.cookieName);
	if (cookie == null) {
		return null;
	}
	String token = cookie.getValue();
	if (!StringUtils.hasLength(token)) {
		return null;
	}
	return new CsrfTokenBean(this.headerName, this.parameterName, token);
}
 
Example #30
Source File: ControllerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void doTestServletForwardingController(ServletForwardingController sfc, boolean include)
		throws Exception {

	HttpServletRequest request = mock(HttpServletRequest.class);
	HttpServletResponse response = mock(HttpServletResponse.class);
	ServletContext context = mock(ServletContext.class);
	RequestDispatcher dispatcher = mock(RequestDispatcher.class);

	given(request.getMethod()).willReturn("GET");
	given(context.getNamedDispatcher("action")).willReturn(dispatcher);
	if (include) {
		given(request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE)).willReturn("somePath");
	}
	else {
		given(request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE)).willReturn(null);
	}

	StaticWebApplicationContext sac = new StaticWebApplicationContext();
	sac.setServletContext(context);
	sfc.setApplicationContext(sac);
	assertNull(sfc.handleRequest(request, response));

	if (include) {
		verify(dispatcher).include(request, response);
	}
	else {
		verify(dispatcher).forward(request, response);
	}
}