Java Code Examples for org.springframework.web.util.WebUtils#getNativeResponse()

The following examples show how to use org.springframework.web.util.WebUtils#getNativeResponse() . 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: ShallowEtagHeaderFilter.java    From spring-analysis-note with MIT License 6 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(), this.writeWeakETag);
		rawResponse.setHeader(HttpHeaders.ETAG, responseETag);
		String requestETag = request.getHeader(HttpHeaders.IF_NONE_MATCH);
		if (requestETag != null && ("*".equals(requestETag) || compareETagHeaderValue(requestETag, responseETag))) {
			rawResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
		}
		else {
			responseWrapper.copyBodyToResponse();
		}
	}
	else {
		responseWrapper.copyBodyToResponse();
	}
}
 
Example 2
Source File: ShallowEtagHeaderFilter.java    From java-technology-stack with MIT License 6 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(), this.writeWeakETag);
		rawResponse.setHeader(HEADER_ETAG, responseETag);
		String requestETag = request.getHeader(HEADER_IF_NONE_MATCH);
		if (requestETag != null && ("*".equals(requestETag) || compareETagHeaderValue(requestETag, responseETag))) {
			rawResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
		}
		else {
			responseWrapper.copyBodyToResponse();
		}
	}
	else {
		responseWrapper.copyBodyToResponse();
	}
}
 
Example 3
Source File: RedisSecurityContextRepository.java    From onetwo with Apache License 2.0 6 votes vote down vote up
private void saveSecurityContext(HttpServletRequest request, HttpServletResponse response, SecurityContext context){
	String sid = getSessionId(request);
	if(StringUtils.isBlank(sid)){
		SaveToSessionResponseWrapper responseWrapper = WebUtils.getNativeResponse(response, SaveToSessionResponseWrapper.class);
		sid = responseWrapper.getSid();
		saveSessionCookies(request, response, sid);
	}
	
	/*LoginUserDetails loginUser = SecurityUtils.getCurrentLoginUser(context);
	if(loginUser!=null){
		loginUser.setToken(sid);
	}*/
	
	BoundValueOperations<String, SecurityContext> bondOps = getSessionBoundOps(sid);
	//当前spring-data-redis版本不支持setex,分成两个操作
	bondOps.set(context);
	setSecurityContextExpireTime(request);
}
 
Example 4
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 5
Source File: RelativeRedirectResponseWrapper.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public static HttpServletResponse wrapIfNecessary(HttpServletResponse response,
		HttpStatus redirectStatus) {

	RelativeRedirectResponseWrapper wrapper =
			WebUtils.getNativeResponse(response, RelativeRedirectResponseWrapper.class);

	return (wrapper != null ? response :
			new RelativeRedirectResponseWrapper(response, redirectStatus));
}
 
Example 6
Source File: CometRequestFilter.java    From Milkomeda with MIT License 5 votes vote down vote up
private void updateResponse(HttpServletResponse response) throws IOException {
    CometResponseWrapper responseWrapper =
            WebUtils.getNativeResponse(response, CometResponseWrapper.class);
    Assert.notNull(responseWrapper, "CometResponseWrapper not found");
    // HttpServletResponse rawResponse = (HttpServletResponse) responseWrapper.getResponse();
    responseWrapper.copyBodyToResponse();
}
 
Example 7
Source File: CometInterceptor.java    From Milkomeda with MIT License 5 votes vote down vote up
@Override
public void afterCompletion(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler, Exception ex) throws Exception {
    if (cometCollectorProperties == null || !cometCollectorProperties.isEnableTag() ||
            CollectionUtils.isEmpty(this.tagCollectorMap) || threadLocal.get() == null) {
        return;
    }
    // 获取ResponseEntity返回值
    Object body = request.getAttribute(CometCollectorResponseBodyAdvice.REQUEST_ATTRIBUTE_BODY);
    if (body == null) {
        // 从ResponseWrapper获取
        CometResponseWrapper responseWrapper =
                WebUtils.getNativeResponse(response, CometResponseWrapper.class);
        if (responseWrapper != null) {
            String content = new String(responseWrapper.getContentAsByteArray(), StandardCharsets.UTF_8);
            if (StringUtils.isEmpty(content)) {
                body = null;
            } else {
                String contentType = responseWrapper.getResponse().getContentType();
                // JSON -> Map
                if (contentType.startsWith(MediaType.APPLICATION_JSON_VALUE)) {
                    body = JSONUtil.parseMap(content, String.class, Object.class);
                } else { // String!
                    body = content;
                }
            }
        }
    }
    this.collectPostLog(response.getStatus(), body, ex);
}
 
Example 8
Source File: RelativeRedirectResponseWrapper.java    From java-technology-stack with MIT License 5 votes vote down vote up
public static HttpServletResponse wrapIfNecessary(HttpServletResponse response,
		HttpStatus redirectStatus) {

	RelativeRedirectResponseWrapper wrapper =
			WebUtils.getNativeResponse(response, RelativeRedirectResponseWrapper.class);

	return (wrapper != null ? response :
			new RelativeRedirectResponseWrapper(response, redirectStatus));
}
 
Example 9
Source File: ShallowEtagHeaderFilter.java    From lams with GNU General Public License v2.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(), this.writeWeakETag);
		rawResponse.setHeader(HEADER_ETAG, responseETag);
		String requestETag = request.getHeader(HEADER_IF_NONE_MATCH);
		if (requestETag != null
				&& (responseETag.equals(requestETag)
				|| responseETag.replaceFirst("^W/", "").equals(requestETag.replaceFirst("^W/", ""))
				|| "*".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 10
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 11
Source File: ServletWebRequest.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public <T> T getNativeResponse(@Nullable Class<T> requiredType) {
	HttpServletResponse response = getResponse();
	return (response != null ? WebUtils.getNativeResponse(response, requiredType) : null);
}
 
Example 12
Source File: CometAspect.java    From Milkomeda with MIT License 4 votes vote down vote up
@SuppressWarnings("rawtypes")
private Object applyAround(CometData cometData, ThreadLocal<CometData> threadLocal, ProceedingJoinPoint joinPoint,
                           HttpServletRequest request, Date requestTime, String name, String tag,
                           Function<Object, Object> mapReturnData) throws Throwable {
    cometData.setRequest(request);
    cometData.setRequestTime(requestTime);
    cometData.setName(name);
    cometData.setTag(tag);
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    cometData.setClazzName(signature.getDeclaringTypeName());
    cometData.setExecMethod(signature.getName());
    Map<String, Object> params = new HashMap<>();
    // 获取参数名
    String[] parameterNames = signature.getParameterNames();
    Object[] args = joinPoint.getArgs();
    if (args !=  null && args.length > 0) {
        for (int i = 0; i < args.length; i++) {
            String argName = parameterNames[i];
            Object argValue = args[i];
            if (hasFilter(argValue)) {
                continue;
            }
            params.put(argName, argValue);
        }
        cometData.setRequestData(JSONUtil.serialize(params));
    }
    try {
        String host = NetworkUtil.getHost();
        cometData.setHost(host);
    } catch (UnknownHostException ignored) {
    }
    if (milkomedaProperties.isShowLog()) {
        log.info("Comet:- before: {}", JSONUtil.serialize(cometData));
    }
    // 外部可以扩展记录自定义数据
    recorder.onRequest(cometData, cometData.getTag(), request, args);
    threadLocal.set(cometData);

    // 执行方法体
    Object returnData = joinPoint.proceed();

    long duration = new Date().getTime() - cometData.getRequestTime().getTime();
    cometData.setDuration(String.valueOf(duration));
    cometData.setStatus(cometProperties.getStatusSuccessCode());
    cometData.setResponseTime(new Date());
    if (returnData != null) {
        // returnData应用map转换类型
        if (mapReturnData != null) {
            returnData = mapReturnData.apply(returnData);
        }

        // 记录返回数据
        if (returnData instanceof ResponseEntity) {
            Object body = ((ResponseEntity) returnData).getBody();
            cometData.setResponseData(body instanceof String ? (String) body : JSONUtil.serialize(body));
        } else {
            cometData.setResponseData(returnData instanceof String ? (String) returnData : JSONUtil.serialize(returnData));
        }
    } else {
        // 读取Response
        if (CometHolder.getCollectorProps() != null && CometHolder.getCollectorProps().isEnable()) {
            CometResponseWrapper responseWrapper =
                    WebUtils.getNativeResponse(WebContext.getResponse(), CometResponseWrapper.class);
            if (responseWrapper != null) {
                cometData.setStatus(WebContext.getResponse().getStatus() == HttpStatus.OK.value() ? cometProperties.getStatusSuccessCode() : cometProperties.getStatusFailCode());
                String content = new String(responseWrapper.getContentAsByteArray(), StandardCharsets.UTF_8);
                cometData.setResponseData(content);
            }
        }
    }

    // 开始回调
    Object returnObj = recorder.onReturn(cometData, returnData);
    // 修正返回值
    returnObj = returnObj == null ? returnData : returnObj;
    if (milkomedaProperties.isShowLog()) {
        log.info("Comet:- afterReturn: {}", JSONUtil.serialize(cometData));
    }
    threadLocal.remove();
    return returnObj;
}
 
Example 13
Source File: ServletWebRequest.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
public <T> T getNativeResponse(@Nullable Class<T> requiredType) {
	HttpServletResponse response = getResponse();
	return (response != null ? WebUtils.getNativeResponse(response, requiredType) : null);
}
 
Example 14
Source File: ServletWebRequest.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public <T> T getNativeResponse(Class<T> requiredType) {
	return WebUtils.getNativeResponse(getResponse(), requiredType);
}
 
Example 15
Source File: ServletWebRequest.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public <T> T getNativeResponse(Class<T> requiredType) {
	return WebUtils.getNativeResponse(getResponse(), requiredType);
}