當前位置: 首頁>>代碼示例>>Java>>正文


Java ServerHttpRequest類代碼示例

本文整理匯總了Java中org.springframework.http.server.ServerHttpRequest的典型用法代碼示例。如果您正苦於以下問題:Java ServerHttpRequest類的具體用法?Java ServerHttpRequest怎麽用?Java ServerHttpRequest使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


ServerHttpRequest類屬於org.springframework.http.server包,在下文中一共展示了ServerHttpRequest類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: beforeBodyWrite

import org.springframework.http.server.ServerHttpRequest; //導入依賴的package包/類
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                              Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                              ServerHttpResponse response) {

    ResponseJSONP responseJsonp = returnType.getMethodAnnotation(ResponseJSONP.class);
    if(responseJsonp == null){
        responseJsonp = returnType.getContainingClass().getAnnotation(ResponseJSONP.class);
    }

    HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
    String callbackMethodName = servletRequest.getParameter(responseJsonp.callback());

    if (!IOUtils.isValidJsonpQueryParam(callbackMethodName)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invalid jsonp parameter value:" + callbackMethodName);
        }
        callbackMethodName = null;
    }

    JSONPObject jsonpObject = new JSONPObject(callbackMethodName);
    jsonpObject.addParameter(body);
    beforeBodyWriteInternal(jsonpObject, selectedContentType, returnType, request, response);
    return jsonpObject;
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:25,代碼來源:JSONPResponseBodyAdvice.java

示例2: beforeHandshake

import org.springframework.http.server.ServerHttpRequest; //導入依賴的package包/類
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
    System.out.println("before handshake");
    ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
    HttpSession session = servletRequest.getServletRequest().getSession(false);
    Long uid = (Long)session.getAttribute("uid");
    if(uid == null){
        return false;
    }

    //如果uid==null,afterConnectionEstablished不執行,協議轉換不成功,報下麵的錯誤
    //websocket.html?uid=1990:56 WebSocket connection to 'ws://localhost:8080/ws?uid=1990' failed: Error during WebSocket handshake: Unexpected response code: 500
    attributes.put("uid", uid);
    return true;

    // 如果這裏返回false,瀏覽器會報下麵這個錯誤
    // WebSocket connection to 'ws://localhost:8080/ws' failed: Error during WebSocket handshake: Unexpected response code: 200
}
 
開發者ID:chang20159,項目名稱:Instant-Messaging,代碼行數:19,代碼來源:HandshakeInterceptor.java

示例3: beforeBodyWrite

import org.springframework.http.server.ServerHttpRequest; //導入依賴的package包/類
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
    Class converterType = returnType.getMethod().getDeclaringClass();
    FilterResponse defaultResponse = returnType.getMethod().getAnnotation(FilterResponse.class);
    if(defaultResponse==null) {
        defaultResponse = (FilterResponse) converterType.getAnnotation(FilterResponse.class);
    }
    String className =converterType.getName();
    logger.debug("beforeBodyWrite - className >" +className +", defaultResponse - > "+defaultResponse);
    if(defaultResponse!=null){
        switch (defaultResponse.type()){
            case defaultFilter:{
                response.getHeaders().add(Constants.defaultResponseHeader,Constants.defaultResponseHeader);
            }
        }
    }
    return body;
}
 
開發者ID:codingapi,項目名稱:filter,代碼行數:18,代碼來源:DefFilterDataResponseHandler.java

示例4: beforeBodyWriteInternal

import org.springframework.http.server.ServerHttpRequest; //導入依賴的package包/類
@Override
protected void beforeBodyWriteInternal(final MappingJacksonValue bodyContainer,
                                       final MediaType contentType,
                                       final MethodParameter returnType,
                                       final ServerHttpRequest request,
                                       final ServerHttpResponse response) {
    final Mutable<Class<?>> viewClass = Mutable.of(View.Anonymous.class);

    if (SecurityContextHolder.getContext().getAuthentication() != null && SecurityContextHolder.getContext().getAuthentication().getAuthorities() != null) {
        final Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();

        viewClass.mutateIf(View.User.class, authorities.stream().anyMatch(o -> o.getAuthority().equals("PRIV_USER")));
        viewClass.mutateIf(View.Moderator.class, authorities.stream().anyMatch(o -> o.getAuthority().equals("PRIV_MODERATOR")));
        viewClass.mutateIf(View.Admin.class, authorities.stream().anyMatch(o -> o.getAuthority().equals("PRIV_ADMIN")));
    }

    bodyContainer.setSerializationView(viewClass.get());
}
 
開發者ID:mhaddon,項目名稱:Sound.je,代碼行數:19,代碼來源:JsonViewConfiguration.java

示例5: buildRequestLog

import org.springframework.http.server.ServerHttpRequest; //導入依賴的package包/類
/**
 * Build log message for request in bound.
 *
 * @param request Request in bound.
 * @return Log message.
 * @since 1.0.0
 */
protected String buildRequestLog(HttpServletRequest request) {
	ServerHttpRequest httpRequest = new ServletServerHttpRequest(request);

	StringBuilder sb = new StringBuilder("Server has received a request").append(StringUtils.LF)
			.append(" > ").append(httpRequest.getMethod()).append(" ").append(httpRequest.getURI()).append
					(StringUtils.LF);

	Map<String, String> headers = httpRequest.getHeaders().toSingleValueMap();
	for (Map.Entry<String, String> entry : headers.entrySet()) {
		sb.append(" > ").append(entry.getKey()).append(": ").append(entry.getValue()).append(StringUtils.LF);
	}

	sb.append(extractRequestPayload(request));

	return sb.toString();
}
 
開發者ID:cmateosl,項目名稱:role-api,代碼行數:24,代碼來源:BaseLoggingFilter.java

示例6: beforeBodyWrite

import org.springframework.http.server.ServerHttpRequest; //導入依賴的package包/類
@Override
public BizRes beforeBodyWrite(BizRes body, MethodParameter returnType, MediaType selectedContentType,
                              Class<? extends HttpMessageConverter<?>> selectedConverterType,
                              ServerHttpRequest request, ServerHttpResponse response) {
    String deviceToken = response.getHeaders().getFirst(requestHeaderProperties.getDeviceToken());
    if (body instanceof ErrorRes) {
        ((ErrorRes) body).setVd(deviceToken);
        return body;
    }
    if (body instanceof SuccessRes) {
        ((SuccessRes) body).setVd(deviceToken);
        return body;
    }
    SuccessRes res = new SuccessRes(body);
    res.setVd(deviceToken);
    return res;
}
 
開發者ID:superkoh,項目名稱:k-framework,代碼行數:18,代碼來源:DefaultResponseBodyHandler.java

示例7: getBodyViaRequestParameterWithRequestEncoding

import org.springframework.http.server.ServerHttpRequest; //導入依賴的package包/類
@Test
public void getBodyViaRequestParameterWithRequestEncoding() throws Exception {
	MockMultipartHttpServletRequest mockRequest = new MockMultipartHttpServletRequest() {

		@Override
		public HttpHeaders getMultipartHeaders(String paramOrFileName) {
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			return headers;
		}
	};
	byte[] bytes = {(byte) 0xC4};
	mockRequest.setParameter("part", new String(bytes, Charset.forName("iso-8859-1")));
	mockRequest.setCharacterEncoding("iso-8859-1");
	ServerHttpRequest request = new RequestPartServletServerHttpRequest(mockRequest, "part");

	byte[] result = FileCopyUtils.copyToByteArray(request.getBody());
	assertArrayEquals(bytes, result);
}
 
開發者ID:langtianya,項目名稱:spring4-understanding,代碼行數:20,代碼來源:RequestPartServletServerHttpRequestTests.java

示例8: beforeBodyWriteInternal

import org.springframework.http.server.ServerHttpRequest; //導入依賴的package包/類
@Override
protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType,
		MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) {

	HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();

	for (String name : this.jsonpQueryParamNames) {
		String value = servletRequest.getParameter(name);
		if (value != null) {
			if (!isValidJsonpQueryParam(value)) {
				if (logger.isDebugEnabled()) {
					logger.debug("Ignoring invalid jsonp parameter value: " + value);
				}
				continue;
			}
			MediaType contentTypeToUse = getContentType(contentType, request, response);
			response.getHeaders().setContentType(contentTypeToUse);
			bodyContainer.setJsonpFunction(value);
			break;
		}
	}
}
 
開發者ID:langtianya,項目名稱:spring4-understanding,代碼行數:23,代碼來源:AbstractJsonpResponseBodyAdvice.java

示例9: testHttpConnectionNonAsync

import org.springframework.http.server.ServerHttpRequest; //導入依賴的package包/類
private void testHttpConnectionNonAsync(long sleepBeforeResponse)
		throws IOException, InterruptedException {
	ServerHttpRequest request = mock(ServerHttpRequest.class);
	given(request.getAsyncRequestControl(this.response))
			.willThrow(new IllegalArgumentException());
	final HttpConnection connection = new HttpConnection(request, this.response);
	final AtomicBoolean responded = new AtomicBoolean();
	Thread connectionThread = new Thread() {

		@Override
		public void run() {
			connection.waitForResponse();
			responded.set(true);
		}

	};
	connectionThread.start();
	assertThat(responded.get()).isFalse();
	Thread.sleep(sleepBeforeResponse);
	connection.respond(HttpStatus.NO_CONTENT);
	connectionThread.join();
	assertThat(responded.get()).isTrue();
}
 
開發者ID:vikrammane23,項目名稱:https-github.com-g0t4-jenkins2-course-spring-boot,代碼行數:24,代碼來源:HttpTunnelServerTests.java

示例10: beforeBodyWriteInternal

import org.springframework.http.server.ServerHttpRequest; //導入依賴的package包/類
@Override
protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer,
		MediaType contentType, MethodParameter returnType,
		ServerHttpRequest request, ServerHttpResponse response) {

	Page<?> page = ((Page<?>) bodyContainer.getValue());

	response.getHeaders().add(CUSTOM_HEADER_META_PAGINATION,
			String.format(PAGE_METADATA_FMT, page.getNumber(), page.getSize(),
					page.getTotalElements(), page.getTotalPages(), page.isFirst(),
					page.isLast()));

	getHttpHeaderLinksString(request, page)
			.filter(StringUtils::isNotEmpty)
			.ifPresent(s -> response.getHeaders().add(HttpHeaders.LINK, s));

	// finally, strip out the actual content and replace it as the body value
	bodyContainer.setValue(page.getContent());
}
 
開發者ID:ssherwood,項目名稱:spring-boot-jpa,代碼行數:20,代碼來源:PageResponseBodyAdvisor.java

示例11: getBodyViaRequestParameter

import org.springframework.http.server.ServerHttpRequest; //導入依賴的package包/類
@Test
public void getBodyViaRequestParameter() throws Exception {
	MockMultipartHttpServletRequest mockRequest = new MockMultipartHttpServletRequest() {

		@Override
		public HttpHeaders getMultipartHeaders(String paramOrFileName) {
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(new MediaType("application", "octet-stream", Charset.forName("iso-8859-1")));
			return headers;
		}
	};
	byte[] bytes = {(byte) 0xC4};
	mockRequest.setParameter("part", new String(bytes, Charset.forName("iso-8859-1")));
	ServerHttpRequest request = new RequestPartServletServerHttpRequest(mockRequest, "part");

	byte[] result = FileCopyUtils.copyToByteArray(request.getBody());
	assertArrayEquals(bytes, result);
}
 
開發者ID:langtianya,項目名稱:spring4-understanding,代碼行數:19,代碼來源:RequestPartServletServerHttpRequestTests.java

示例12: beforeHandshake

import org.springframework.http.server.ServerHttpRequest; //導入依賴的package包/類
@Override
public boolean beforeHandshake(final ServerHttpRequest request, final ServerHttpResponse response, final WebSocketHandler wsHandler, final Map<String, Object> attributes) throws Exception
{
	// UserSession.getCurrent().assertLoggedIn();
	// return true;

	final UserSession userSession = UserSession.getCurrentOrNull();
	if (userSession == null)
	{
		logger.warn("Websocket connection not allowed (missing userSession)");
		response.setStatusCode(HttpStatus.UNAUTHORIZED);
		return false;
	}

	if (!userSession.isLoggedIn())
	{
		logger.warn("Websocket connection not allowed (not logged in) - userSession={}", userSession);
		response.setStatusCode(HttpStatus.UNAUTHORIZED);
		return false;
	}

	return true;
}
 
開發者ID:metasfresh,項目名稱:metasfresh-webui-api,代碼行數:24,代碼來源:WebSocketConfig.java

示例13: checkOrigin

import org.springframework.http.server.ServerHttpRequest; //導入依賴的package包/類
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;
}
 
開發者ID:langtianya,項目名稱:spring4-understanding,代碼行數:18,代碼來源:AbstractSockJsService.java

示例14: handledByDispatcher

import org.springframework.http.server.ServerHttpRequest; //導入依賴的package包/類
@Test
public void handledByDispatcher() throws Exception {
	HttpServletRequest request = new MockHttpServletRequest("GET", "/hello");
	HttpServletResponse response = new MockHttpServletResponse();
	willReturn(true).given(this.dispatcher).handle(any(ServerHttpRequest.class),
			any(ServerHttpResponse.class));
	this.filter.doFilter(request, response, this.chain);
	verifyZeroInteractions(this.chain);
	verify(this.dispatcher).handle(this.serverRequestCaptor.capture(),
			this.serverResponseCaptor.capture());
	ServerHttpRequest dispatcherRequest = this.serverRequestCaptor.getValue();
	ServletServerHttpRequest actualRequest = (ServletServerHttpRequest) dispatcherRequest;
	ServerHttpResponse dispatcherResponse = this.serverResponseCaptor.getValue();
	ServletServerHttpResponse actualResponse = (ServletServerHttpResponse) dispatcherResponse;
	assertThat(actualRequest.getServletRequest()).isEqualTo(request);
	assertThat(actualResponse.getServletResponse()).isEqualTo(response);
}
 
開發者ID:philwebb,項目名稱:spring-boot-concourse,代碼行數:18,代碼來源:DispatcherFilterTests.java

示例15: handleSuccessiveRequest

import org.springframework.http.server.ServerHttpRequest; //導入依賴的package包/類
/**
 * Handle all requests, except the first one, to receive messages on a SockJS
 * HTTP transport based session.
 * <p>Long polling-based transports (e.g. "xhr", "jsonp") complete the request
 * after writing any buffered message frames (or the next one). Streaming-based
 * transports ("xhr_streaming", "eventsource", and "htmlfile") leave the
 * response open longer for further streaming of message frames but will also
 * close it eventually after some amount of data has been sent.
 * @param request the current request
 * @param response the current response
 * @param frameFormat the transport-specific SocksJS frame format to use
 */
public void handleSuccessiveRequest(ServerHttpRequest request, ServerHttpResponse response,
		SockJsFrameFormat frameFormat) throws SockJsException {

	synchronized (this.responseLock) {
		try {
			if (isClosed()) {
				response.getBody().write(SockJsFrame.closeFrameGoAway().getContentBytes());
				return;
			}
			this.response = response;
			this.frameFormat = frameFormat;
			this.asyncRequestControl = request.getAsyncRequestControl(response);
			this.asyncRequestControl.start(-1);

			disableShallowEtagHeaderFilter(request);

			handleRequestInternal(request, response, false);
			this.readyToSend = isActive();
		}
		catch (Throwable ex) {
			tryCloseWithSockJsTransportError(ex, CloseStatus.SERVER_ERROR);
			throw new SockJsTransportFailureException("Failed to handle SockJS receive request", getId(), ex);
		}
	}
}
 
開發者ID:langtianya,項目名稱:spring4-understanding,代碼行數:38,代碼來源:AbstractHttpSockJsSession.java


注:本文中的org.springframework.http.server.ServerHttpRequest類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。