当前位置: 首页>>代码示例>>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;未经允许,请勿转载。