Java Code Examples for org.springframework.http.server.ServletServerHttpResponse#getHeaders()

The following examples show how to use org.springframework.http.server.ServletServerHttpResponse#getHeaders() . 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: FastJsonResponseUtil.java    From stategen with GNU Affero General Public License v3.0 6 votes vote down vote up
@SuppressWarnings("resource")
public static void writeResponse(Object result) {
    HttpServletResponse httpServletResponse = ServletContextUtil.getHttpServletResponse();
    ServletServerHttpResponse servletServerHttpResponse = new ServletServerHttpResponse(httpServletResponse);
    HttpHeaders headers = servletServerHttpResponse.getHeaders();
    
    httpServletResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
    httpServletResponse.setStatus(HttpStatus.OK.value());
    try {
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        FASTJSON_HTTP_MESSAGE_CONVERTOR.write(result, headers.getContentType(), new HttpOutputMessage() {
            @Override
            public OutputStream getBody() throws IOException {
                return outputStream;
            }

            @Override
            public HttpHeaders getHeaders() {
                return headers;
            }
        });
    } catch (HttpMessageNotWritableException | IOException e) {
        logger.error("internal error", e);
    }
}
 
Example 2
Source File: AbstractMessageConverterMethodProcessor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Check if the path has a file extension and whether the extension is
 * either {@link #WHITELISTED_EXTENSIONS whitelisted} or explicitly
 * {@link ContentNegotiationManager#getAllFileExtensions() registered}.
 * If not, and the status is in the 2xx range, a 'Content-Disposition'
 * header with a safe attachment file name ("f.txt") is added to prevent
 * RFD exploits.
 */
private void addContentDispositionHeader(ServletServerHttpRequest request, ServletServerHttpResponse response) {
	HttpHeaders headers = response.getHeaders();
	if (headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
		return;
	}

	try {
		int status = response.getServletResponse().getStatus();
		if (status < 200 || status > 299) {
			return;
		}
	}
	catch (Throwable ex) {
		// ignore
	}

	HttpServletRequest servletRequest = request.getServletRequest();
	String requestUri = rawUrlPathHelper.getOriginatingRequestUri(servletRequest);

	int index = requestUri.lastIndexOf('/') + 1;
	String filename = requestUri.substring(index);
	String pathParams = "";

	index = filename.indexOf(';');
	if (index != -1) {
		pathParams = filename.substring(index);
		filename = filename.substring(0, index);
	}

	filename = decodingUrlPathHelper.decodeRequestString(servletRequest, filename);
	String ext = StringUtils.getFilenameExtension(filename);

	pathParams = decodingUrlPathHelper.decodeRequestString(servletRequest, pathParams);
	String extInPathParams = StringUtils.getFilenameExtension(pathParams);

	if (!safeExtension(servletRequest, ext) || !safeExtension(servletRequest, extInPathParams)) {
		headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=f.txt");
	}
}
 
Example 3
Source File: HttpEntityMethodProcessor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private boolean isResourceNotModified(ServletServerHttpRequest request, ServletServerHttpResponse response) {
	ServletWebRequest servletWebRequest =
			new ServletWebRequest(request.getServletRequest(), response.getServletResponse());
	HttpHeaders responseHeaders = response.getHeaders();
	String etag = responseHeaders.getETag();
	long lastModifiedTimestamp = responseHeaders.getLastModified();
	if (request.getMethod() == HttpMethod.GET || request.getMethod() == HttpMethod.HEAD) {
		responseHeaders.remove(HttpHeaders.ETAG);
		responseHeaders.remove(HttpHeaders.LAST_MODIFIED);
	}

	return servletWebRequest.checkNotModified(etag, lastModifiedTimestamp);
}
 
Example 4
Source File: AbstractMessageConverterMethodProcessor.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Check if the path has a file extension and whether the extension is
 * either {@link #WHITELISTED_EXTENSIONS whitelisted} or explicitly
 * {@link ContentNegotiationManager#getAllFileExtensions() registered}.
 * If not, and the status is in the 2xx range, a 'Content-Disposition'
 * header with a safe attachment file name ("f.txt") is added to prevent
 * RFD exploits.
 */
private void addContentDispositionHeader(ServletServerHttpRequest request, ServletServerHttpResponse response) {
	HttpHeaders headers = response.getHeaders();
	if (headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
		return;
	}

	try {
		int status = response.getServletResponse().getStatus();
		if (status < 200 || status > 299) {
			return;
		}
	}
	catch (Throwable ex) {
		// ignore
	}

	HttpServletRequest servletRequest = request.getServletRequest();
	String requestUri = rawUrlPathHelper.getOriginatingRequestUri(servletRequest);

	int index = requestUri.lastIndexOf('/') + 1;
	String filename = requestUri.substring(index);
	String pathParams = "";

	index = filename.indexOf(';');
	if (index != -1) {
		pathParams = filename.substring(index);
		filename = filename.substring(0, index);
	}

	filename = decodingUrlPathHelper.decodeRequestString(servletRequest, filename);
	String ext = StringUtils.getFilenameExtension(filename);

	pathParams = decodingUrlPathHelper.decodeRequestString(servletRequest, pathParams);
	String extInPathParams = StringUtils.getFilenameExtension(pathParams);

	if (!safeExtension(servletRequest, ext) || !safeExtension(servletRequest, extInPathParams)) {
		headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=f.txt");
	}
}
 
Example 5
Source File: HttpEntityMethodProcessor.java    From java-technology-stack with MIT License 5 votes vote down vote up
private boolean isResourceNotModified(ServletServerHttpRequest request, ServletServerHttpResponse response) {
	ServletWebRequest servletWebRequest =
			new ServletWebRequest(request.getServletRequest(), response.getServletResponse());
	HttpHeaders responseHeaders = response.getHeaders();
	String etag = responseHeaders.getETag();
	long lastModifiedTimestamp = responseHeaders.getLastModified();
	if (request.getMethod() == HttpMethod.GET || request.getMethod() == HttpMethod.HEAD) {
		responseHeaders.remove(HttpHeaders.ETAG);
		responseHeaders.remove(HttpHeaders.LAST_MODIFIED);
	}

	return servletWebRequest.checkNotModified(etag, lastModifiedTimestamp);
}
 
Example 6
Source File: PropertiesHandlerMethodReturnValueHandler.java    From SpringAll with MIT License 5 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
    Properties properties = (Properties) returnValue;

    ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest;

    HttpServletResponse response = servletWebRequest.getResponse();
    ServletServerHttpResponse servletServerHttpResponse = new ServletServerHttpResponse(response);

    // 获取请求头
    HttpHeaders headers = servletServerHttpResponse.getHeaders();

    MediaType contentType = headers.getContentType();
    // 获取编码
    Charset charset = null;
    if (contentType != null) {
        charset = contentType.getCharset();
    }

    charset = charset == null ? Charset.forName("UTF-8") : charset;

    // 获取请求体
    OutputStream body = servletServerHttpResponse.getBody();
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(body, charset);

    properties.store(outputStreamWriter, "Serialized by PropertiesHandlerMethodReturnValueHandler#handleReturnValue");

    // 告诉 Spring MVC 请求已经处理完毕
    mavContainer.setRequestHandled(true);
}
 
Example 7
Source File: AbstractMessageConverterMethodProcessor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Check if the path has a file extension and whether the extension is
 * either {@link #WHITELISTED_EXTENSIONS whitelisted} or explicitly
 * {@link ContentNegotiationManager#getAllFileExtensions() registered}.
 * If not, and the status is in the 2xx range, a 'Content-Disposition'
 * header with a safe attachment file name ("f.txt") is added to prevent
 * RFD exploits.
 */
private void addContentDispositionHeader(ServletServerHttpRequest request, ServletServerHttpResponse response) {
	HttpHeaders headers = response.getHeaders();
	if (headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
		return;
	}

	try {
		int status = response.getServletResponse().getStatus();
		if (status < 200 || status > 299) {
			return;
		}
	}
	catch (Throwable ex) {
		// ignore
	}

	HttpServletRequest servletRequest = request.getServletRequest();
	String requestUri = RAW_URL_PATH_HELPER.getOriginatingRequestUri(servletRequest);

	int index = requestUri.lastIndexOf('/') + 1;
	String filename = requestUri.substring(index);
	String pathParams = "";

	index = filename.indexOf(';');
	if (index != -1) {
		pathParams = filename.substring(index);
		filename = filename.substring(0, index);
	}

	filename = DECODING_URL_PATH_HELPER.decodeRequestString(servletRequest, filename);
	String ext = StringUtils.getFilenameExtension(filename);

	pathParams = DECODING_URL_PATH_HELPER.decodeRequestString(servletRequest, pathParams);
	String extInPathParams = StringUtils.getFilenameExtension(pathParams);

	if (!safeExtension(servletRequest, ext) || !safeExtension(servletRequest, extInPathParams)) {
		headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=f.txt");
	}
}
 
Example 8
Source File: HttpEntityMethodProcessor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private boolean isResourceNotModified(ServletServerHttpRequest inputMessage, ServletServerHttpResponse outputMessage) {
	ServletWebRequest servletWebRequest =
			new ServletWebRequest(inputMessage.getServletRequest(), outputMessage.getServletResponse());
	HttpHeaders responseHeaders = outputMessage.getHeaders();
	String etag = responseHeaders.getETag();
	long lastModifiedTimestamp = responseHeaders.getLastModified();
	if (inputMessage.getMethod() == HttpMethod.GET || inputMessage.getMethod() == HttpMethod.HEAD) {
		responseHeaders.remove(HttpHeaders.ETAG);
		responseHeaders.remove(HttpHeaders.LAST_MODIFIED);
	}

	return servletWebRequest.checkNotModified(etag, lastModifiedTimestamp);
}
 
Example 9
Source File: HttpEntityMethodProcessor.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	mavContainer.setRequestHandled(true);
	if (returnValue == null) {
		return;
	}

	ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
	ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);

	Assert.isInstanceOf(HttpEntity.class, returnValue);
	HttpEntity<?> responseEntity = (HttpEntity<?>) returnValue;

	HttpHeaders outputHeaders = outputMessage.getHeaders();
	HttpHeaders entityHeaders = responseEntity.getHeaders();
	if (!entityHeaders.isEmpty()) {
		entityHeaders.forEach((key, value) -> {
			if (HttpHeaders.VARY.equals(key) && outputHeaders.containsKey(HttpHeaders.VARY)) {
				List<String> values = getVaryRequestHeadersToAdd(outputHeaders, entityHeaders);
				if (!values.isEmpty()) {
					outputHeaders.setVary(values);
				}
			}
			else {
				outputHeaders.put(key, value);
			}
		});
	}

	if (responseEntity instanceof ResponseEntity) {
		int returnStatus = ((ResponseEntity<?>) responseEntity).getStatusCodeValue();
		outputMessage.getServletResponse().setStatus(returnStatus);
		if (returnStatus == 200) {
			if (SAFE_METHODS.contains(inputMessage.getMethod())
					&& isResourceNotModified(inputMessage, outputMessage)) {
				// Ensure headers are flushed, no body should be written.
				outputMessage.flush();
				ShallowEtagHeaderFilter.disableContentCaching(inputMessage.getServletRequest());
				// Skip call to converters, as they may update the body.
				return;
			}
		}
		else if (returnStatus / 100 == 3) {
			String location = outputHeaders.getFirst("location");
			if (location != null) {
				saveFlashAttributes(mavContainer, webRequest, location);
			}
		}
	}

	// Try even with null body. ResponseBodyAdvice could get involved.
	writeWithMessageConverters(responseEntity.getBody(), returnType, inputMessage, outputMessage);

	// Ensure headers are flushed even if no body was written.
	outputMessage.flush();
}
 
Example 10
Source File: HttpEntityMethodProcessor.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	mavContainer.setRequestHandled(true);
	if (returnValue == null) {
		return;
	}

	ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
	ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);

	Assert.isInstanceOf(HttpEntity.class, returnValue);
	HttpEntity<?> responseEntity = (HttpEntity<?>) returnValue;

	HttpHeaders outputHeaders = outputMessage.getHeaders();
	HttpHeaders entityHeaders = responseEntity.getHeaders();
	if (!entityHeaders.isEmpty()) {
		entityHeaders.forEach((key, value) -> {
			if (HttpHeaders.VARY.equals(key) && outputHeaders.containsKey(HttpHeaders.VARY)) {
				List<String> values = getVaryRequestHeadersToAdd(outputHeaders, entityHeaders);
				if (!values.isEmpty()) {
					outputHeaders.setVary(values);
				}
			}
			else {
				outputHeaders.put(key, value);
			}
		});
	}

	if (responseEntity instanceof ResponseEntity) {
		int returnStatus = ((ResponseEntity<?>) responseEntity).getStatusCodeValue();
		outputMessage.getServletResponse().setStatus(returnStatus);
		if (returnStatus == 200) {
			if (SAFE_METHODS.contains(inputMessage.getMethod())
					&& isResourceNotModified(inputMessage, outputMessage)) {
				// Ensure headers are flushed, no body should be written.
				outputMessage.flush();
				// Skip call to converters, as they may update the body.
				return;
			}
		}
		else if (returnStatus / 100 == 3) {
			String location = outputHeaders.getFirst("location");
			if (location != null) {
				saveFlashAttributes(mavContainer, webRequest, location);
			}
		}
	}

	// Try even with null body. ResponseBodyAdvice could get involved.
	writeWithMessageConverters(responseEntity.getBody(), returnType, inputMessage, outputMessage);

	// Ensure headers are flushed even if no body was written.
	outputMessage.flush();
}
 
Example 11
Source File: HttpEntityMethodProcessor.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
		ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

	mavContainer.setRequestHandled(true);
	if (returnValue == null) {
		return;
	}

	ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
	ServletServerHttpResponse outputMessage = createOutputMessage(webRequest);

	Assert.isInstanceOf(HttpEntity.class, returnValue);
	HttpEntity<?> responseEntity = (HttpEntity<?>) returnValue;

	HttpHeaders outputHeaders = outputMessage.getHeaders();
	HttpHeaders entityHeaders = responseEntity.getHeaders();
	if (!entityHeaders.isEmpty()) {
		for (Map.Entry<String, List<String>> entry : entityHeaders.entrySet()) {
			if (HttpHeaders.VARY.equals(entry.getKey()) && outputHeaders.containsKey(HttpHeaders.VARY)) {
				List<String> values = getVaryRequestHeadersToAdd(outputHeaders, entityHeaders);
				if (!values.isEmpty()) {
					outputHeaders.setVary(values);
				}
			}
			else {
				outputHeaders.put(entry.getKey(), entry.getValue());
			}
		}
	}

	if (responseEntity instanceof ResponseEntity) {
		int returnStatus = ((ResponseEntity<?>) responseEntity).getStatusCodeValue();
		outputMessage.getServletResponse().setStatus(returnStatus);
		if (returnStatus == 200) {
			if (isResourceNotModified(inputMessage, outputMessage)) {
				// Ensure headers are flushed, no body should be written.
				outputMessage.flush();
				// Skip call to converters, as they may update the body.
				return;
			}
		}
	}

	// Try even with null body. ResponseBodyAdvice could get involved.
	writeWithMessageConverters(responseEntity.getBody(), returnType, inputMessage, outputMessage);

	// Ensure headers are flushed even if no body was written.
	outputMessage.flush();
}
 
Example 12
Source File: AbstractMessageConverterMethodProcessor.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Check if the path has a file extension and whether the extension is
 * either {@link #WHITELISTED_EXTENSIONS whitelisted} or explicitly
 * {@link ContentNegotiationManager#getAllFileExtensions() registered}.
 * If not, and the status is in the 2xx range, a 'Content-Disposition'
 * header with a safe attachment file name ("f.txt") is added to prevent
 * RFD exploits.
 */
private void addContentDispositionHeader(ServletServerHttpRequest request,
		ServletServerHttpResponse response) {

	HttpHeaders headers = response.getHeaders();
	if (headers.containsKey(HttpHeaders.CONTENT_DISPOSITION)) {
		return;
	}

	try {
		int status = response.getServletResponse().getStatus();
		if (status < 200 || status > 299) {
			return;
		}
	}
	catch (Throwable ex) {
		// Ignore
	}

	HttpServletRequest servletRequest = request.getServletRequest();
	String requestUri = RAW_URL_PATH_HELPER.getOriginatingRequestUri(servletRequest);

	int index = requestUri.lastIndexOf('/') + 1;
	String filename = requestUri.substring(index);
	String pathParams = "";

	index = filename.indexOf(';');
	if (index != -1) {
		pathParams = filename.substring(index);
		filename = filename.substring(0, index);
	}

	filename = DECODING_URL_PATH_HELPER.decodeRequestString(servletRequest, filename);
	String ext = StringUtils.getFilenameExtension(filename);

	pathParams = DECODING_URL_PATH_HELPER.decodeRequestString(servletRequest, pathParams);
	String extInPathParams = StringUtils.getFilenameExtension(pathParams);

	if (!safeExtension(servletRequest, ext) || !safeExtension(servletRequest, extInPathParams)) {
		headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline;filename=f.txt");
	}
}