Java Code Examples for javax.servlet.http.HttpServletResponse#getHeader()

The following examples show how to use javax.servlet.http.HttpServletResponse#getHeader() . These examples are extracted from open source projects. 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 Project: lemon   File: CorsFilter.java    License: Apache License 2.0 6 votes vote down vote up
public void doFilter(ServletRequest req, ServletResponse res,
        FilterChain chain) throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    String url = request.getHeader("Origin");

    if (!StringUtils.isEmpty(url)) {
        String val = response.getHeader("Access-Control-Allow-Origin");

        if (StringUtils.isEmpty(val)) {
            response.addHeader("Access-Control-Allow-Origin", url);
            response.addHeader("Access-Control-Allow-Credentials", "true");
        }
    }

    chain.doFilter(req, res);
}
 
Example 2
Source Project: jvue-admin   File: RestLogoutSuccessHandler.java    License: MIT License 6 votes vote down vote up
@Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
            Authentication authentication) throws IOException, ServletException {
        
        // 根据不同的Accept返回不同类型值
    	String accept = response.getHeader("accept");
    	if (MediaType.APPLICATION_JSON_UTF8_VALUE.equalsIgnoreCase(accept)
         		|| MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(accept)) {
	        String result = objectMapper.writeValueAsString(BaseModel.ok(""));
	        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
			response.getWriter().write(result);
        } else {
        	// 画面跳转等处理 
        	super.handle(request, response, authentication);
        }
		
        //jwtTokenUtil.expireToken(token);
//        if (authorization != null) {
//            userService.logout(authorization);
//        }
    }
 
Example 3
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
		AuthenticationException exception) throws IOException, ServletException {
	// do nth.
	// TODO 处理登录失败N次后,账号锁定等

       // 根据不同的Accept返回不同类型值
	
   	String accept = response.getHeader("accept");
   	logger.info("accept {}",accept);
   	
       if (MediaType.APPLICATION_JSON_UTF8_VALUE.equalsIgnoreCase(accept)
       		|| MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(accept)) {
		logger.info("login faild ");
		String result = objectMapper.writeValueAsString(BaseModel.error("1", exception.getMessage()));
		response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
		response.getWriter().write(result);
       } else {
       	super.onAuthenticationFailure(request, response, exception);
       }
}
 
Example 4
@RequestMapping(value = "bundle", method = RequestMethod.GET)
public void getLanguageBundle(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType(ServletUtils.CT_JS);
    final LanguageBundle bundle = getBundle(request);

    // whether the generated ETag should be weak
    // SPEC: length of W/ + " + 0 + 32bits md5 hash + "
    String responseETag = String.format("W/\"0%s\"", bundle.getBundleHash());
    response.setHeader(HEADER_ETAG, responseETag);

    // 无缓存
    String cacheControl = response.getHeader(HEADER_CACHE_CONTROL);
    if (cacheControl != null && cacheControl.contains(DIRECTIVE_NO_STORE)) {
        ServletUtils.write(response, "__LANGBUNDLE__ = " + bundle.toJSON().toJSONString());
        return;
    }

    String requestETag = request.getHeader(HEADER_IF_NONE_MATCH);
    if (requestETag != null && ("*".equals(requestETag) || responseETag.equals(requestETag) ||
            responseETag.replaceFirst("^W/", "").equals(requestETag.replaceFirst("^W/", "")))) {
        response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
    } else {
        ServletUtils.write(response, "__LANGBUNDLE__ = " + bundle.toJSON().toJSONString());
    }
}
 
Example 5
/**
 * Indicates whether the given request and response are eligible for ETag generation.
 * <p>The default implementation returns {@code true} if all conditions match:
 * <ul>
 * <li>response status codes in the {@code 2xx} series</li>
 * <li>request method is a GET</li>
 * <li>response Cache-Control header is not set or does not contain a "no-store" directive</li>
 * </ul>
 * @param request the HTTP request
 * @param response the HTTP response
 * @param responseStatusCode the HTTP response status code
 * @param inputStream the response body
 * @return {@code true} if eligible for ETag generation; {@code false} otherwise
 */
protected boolean isEligibleForEtag(HttpServletRequest request, HttpServletResponse response,
		int responseStatusCode, InputStream inputStream) {

	String method = request.getMethod();
	if (responseStatusCode >= 200 && responseStatusCode < 300
			&& HttpMethod.GET.matches(method)) {

		String cacheControl = null;
		if (servlet3Present) {
			cacheControl = response.getHeader(HEADER_CACHE_CONTROL);
		}
		if (cacheControl == null || !cacheControl.contains(DIRECTIVE_NO_STORE)) {
			return true;
		}
	}
	return false;
}
 
Example 6
Source Project: spectator   File: IpcServletFilter.java    License: Apache License 2.0 6 votes vote down vote up
private void addIfNotPresent(HttpServletResponse httpRes, String name, String value) {
  if (httpRes.getHeader(name) == null) {
    httpRes.addHeader(name, value);
  }
}
 
Example 7
private static String getHeaderValueInternal(HttpServletResponse httpResponse, HttpHeader header) {
	if (httpResponse == null) {
		return null;
	}
	String headerName = header.getName();
	return httpResponse.getHeader(headerName);
}
 
Example 8
Source Project: spring-analysis-note   File: ServletWebRequest.java    License: MIT License 5 votes vote down vote up
@Override
public boolean checkNotModified(@Nullable String etag, long lastModifiedTimestamp) {
	HttpServletResponse response = getResponse();
	if (this.notModified || (response != null && HttpStatus.OK.value() != response.getStatus())) {
		return this.notModified;
	}

	// Evaluate conditions in order of precedence.
	// See https://tools.ietf.org/html/rfc7232#section-6

	if (validateIfUnmodifiedSince(lastModifiedTimestamp)) {
		if (this.notModified && response != null) {
			response.setStatus(HttpStatus.PRECONDITION_FAILED.value());
		}
		return this.notModified;
	}

	boolean validated = validateIfNoneMatch(etag);
	if (!validated) {
		validateIfModifiedSince(lastModifiedTimestamp);
	}

	// Update response
	if (response != null) {
		boolean isHttpGetOrHead = SAFE_METHODS.contains(getRequest().getMethod());
		if (this.notModified) {
			response.setStatus(isHttpGetOrHead ?
					HttpStatus.NOT_MODIFIED.value() : HttpStatus.PRECONDITION_FAILED.value());
		}
		if (isHttpGetOrHead) {
			if (lastModifiedTimestamp > 0 && parseDateValue(response.getHeader(HttpHeaders.LAST_MODIFIED)) == -1) {
				response.setDateHeader(HttpHeaders.LAST_MODIFIED, lastModifiedTimestamp);
			}
			if (StringUtils.hasLength(etag) && response.getHeader(HttpHeaders.ETAG) == null) {
				response.setHeader(HttpHeaders.ETAG, padEtagIfNecessary(etag));
			}
		}
	}

	return this.notModified;
}
 
Example 9
@Override
@SuppressWarnings("resource")
public boolean processRequest(@Nullable CorsConfiguration config, HttpServletRequest request,
		HttpServletResponse response) throws IOException {

	response.addHeader(HttpHeaders.VARY, HttpHeaders.ORIGIN);
	response.addHeader(HttpHeaders.VARY, HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD);
	response.addHeader(HttpHeaders.VARY, HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS);

	if (!CorsUtils.isCorsRequest(request)) {
		return true;
	}

	if (response.getHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN) != null) {
		logger.trace("Skip: response already contains \"Access-Control-Allow-Origin\"");
		return true;
	}

	boolean preFlightRequest = CorsUtils.isPreFlightRequest(request);
	if (config == null) {
		if (preFlightRequest) {
			rejectRequest(new ServletServerHttpResponse(response));
			return false;
		}
		else {
			return true;
		}
	}

	return handleInternal(new ServletServerHttpRequest(request), new ServletServerHttpResponse(response), config, preFlightRequest);
}
 
Example 10
Source Project: odo   File: PluginHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static void writeResponseContent(HttpServletResponse response, String content) throws IOException {
    // check to see if this is chunked
    boolean chunked = false;
    if (response.containsHeader(PluginHelper.STRING_TRANSFER_ENCODING)
            && response.getHeader(PluginHelper.STRING_TRANSFER_ENCODING).compareTo("chunked") == 0) {
        response.setHeader(PluginHelper.STRING_CONNECTION, PluginHelper.STRING_CHUNKED);
        chunked = true;
    }

    // check to see if this content is supposed to be compressed
    // if so recompress it
    boolean isEncoded = false;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    if (response.getHeader("content-encoding") != null &&
            response.getHeader("content-encoding").equals("gzip")) {
        // GZIP the data
        isEncoded = true;
        GZIPOutputStream gzip = new GZIPOutputStream(out);
        gzip.write(content.getBytes());
        gzip.close();
        out.close();
    } else if (response.getHeader("content-encoding") != null &&
            response.getHeader("content-encoding").equals("deflate")) {
        // Deflate the data
        isEncoded = true;
        Deflater compressor = new Deflater();
        compressor.setInput(content.getBytes());
        compressor.finish();

        byte[] buffer = new byte[1024];
        while (!compressor.finished()) {
            int count = compressor.deflate(buffer);
            out.write(buffer, 0, count);
        }
        out.close();
        compressor.end();
    }


    // don't do this if we got a HTTP 304 since there is no data to send back
    if (response.getStatus() != HttpServletResponse.SC_NOT_MODIFIED) {
        if (!chunked) {
            // change the content length header to the new length
            if (content != null && !isEncoded) {
                response.setContentLength(content.getBytes().length);
            } else if (isEncoded) {
                response.setContentLength(out.toByteArray().length);
            }
        }

        OutputStream outputStreamClientResponse = response.getOutputStream();
        response.resetBuffer();

        if (content != null && !isEncoded) {
            outputStreamClientResponse.write(content.getBytes());
        } else if (isEncoded) {
            outputStreamClientResponse.write(out.toByteArray());
        }
    }
}
 
Example 11
@Override
public boolean checkNotModified(@Nullable String etag, long lastModifiedTimestamp) {
	HttpServletResponse response = getResponse();
	if (this.notModified || (response != null && HttpStatus.OK.value() != response.getStatus())) {
		return this.notModified;
	}

	// Evaluate conditions in order of precedence.
	// See https://tools.ietf.org/html/rfc7232#section-6

	if (validateIfUnmodifiedSince(lastModifiedTimestamp)) {
		if (this.notModified && response != null) {
			response.setStatus(HttpStatus.PRECONDITION_FAILED.value());
		}
		return this.notModified;
	}

	boolean validated = validateIfNoneMatch(etag);
	if (!validated) {
		validateIfModifiedSince(lastModifiedTimestamp);
	}

	// Update response
	if (response != null) {
		boolean isHttpGetOrHead = SAFE_METHODS.contains(getRequest().getMethod());
		if (this.notModified) {
			response.setStatus(isHttpGetOrHead ?
					HttpStatus.NOT_MODIFIED.value() : HttpStatus.PRECONDITION_FAILED.value());
		}
		if (isHttpGetOrHead) {
			if (lastModifiedTimestamp > 0 && parseDateValue(response.getHeader(LAST_MODIFIED)) == -1) {
				response.setDateHeader(LAST_MODIFIED, lastModifiedTimestamp);
			}
			if (StringUtils.hasLength(etag) && response.getHeader(ETAG) == null) {
				response.setHeader(ETAG, padEtagIfNecessary(etag));
			}
		}
	}

	return this.notModified;
}
 
Example 12
protected void forwardResponse(final Routes.Route route, final Response response,
                               final HttpServletRequest request, final HttpServletResponse resp,
                               final Function<InputStream, InputStream> responseRewriter) throws IOException {
    final int status = response.getStatus();
    resp.setStatus(status);
    forwardHeaders(route, response, resp);
    if (status == HttpServletResponse.SC_NOT_MODIFIED && resp.getHeader(HttpHeaders.CONTENT_LENGTH) == null) {
        resp.setIntHeader(HttpHeaders.CONTENT_LENGTH, 0);
    }
    forwardCookies(route, response, resp);
    writeOutput(resp, responseRewriter.apply(response.readEntity(InputStream.class)));
}
 
Example 13
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
		Authentication authentication) throws IOException, ServletException {

       // 根据不同的Accept返回不同类型值
   	String accept = response.getHeader("accept");
   	if (MediaType.APPLICATION_JSON_UTF8_VALUE.equalsIgnoreCase(accept)
        		|| MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(accept)) {
   		Object principal = authentication.getPrincipal();
   		
   		// TODO 异步写登录日志等
		if (principal != null) {
			if (principal instanceof JwtUserDetails) {

				JwtUserDetails userDetail = (JwtUserDetails)principal;

				JvueUserInfo userInfo = new JvueUserInfo();
				userInfo.setUsername(userDetail.getUsername());
				userInfo.setEmail(userDetail.getEmail());
				userInfo.setNickname(userDetail.getNickname());
				String result = objectMapper.writeValueAsString(BaseModel.ok(userInfo));
				response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
				response.getWriter().write(result);
			}
		}
        clearAuthenticationAttributes(request);
	} else {
		super.onAuthenticationSuccess(request, response, authentication);
	}
       
}
 
Example 14
static String getHeader(HttpServletRequest request, HttpServletResponse response,
		String name) {
	String value = request.getHeader(name);
	return value != null ? value : response.getHeader(name);
}
 
Example 15
private boolean isHeaderAbsent(HttpServletResponse response, String header) {
	if (response == null || !servlet3Present) {
		// Can't check response.getHeader(header) - let's assume it's not set
		return true;
	}
	return (response.getHeader(header) == null);
}
 
Example 16
private boolean isHeaderAbsent(HttpServletResponse response, String header) {
	if (response == null || !servlet3Present) {
		// Can't check response.getHeader(header) - let's assume it's not set
		return true;
	}
	return (response.getHeader(header) == null);
}
 
Example 17
Source Project: joynr   File: TestRequestDispatcher.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void doHandle(String target,
                     Request baseRequest,
                     HttpServletRequest request,
                     HttpServletResponse response) throws IOException, ServletException {

    String sessionId = request.getRequestedSessionId();

    if (sessionId == null) {
        String contextPath = forwardRoundRobin(baseRequest, response);

        // check if a session has been created in this request
        String location = response.getHeader("Location");
        if (location != null && Utilities.isSessionEncodedInUrl(location, "jsessionid")) {
            String createdSessionId = Utilities.getSessionId(location, "jsessionid");

            ClusterNode sessionCreatingInstance = getSessionCreatingServerInstance(createdSessionId);

            if (sessionCreatingInstance != null) {
                sessionStore.put(createdSessionId, sessionCreatingInstance.getContextPath());
                logger.debug("Request created a session encoded url that was created at server instance {}. Stored session ID {} for that instance",
                             sessionCreatingInstance.getContextPath(),
                             createdSessionId);
            } else {
                sessionStore.put(createdSessionId, contextPath);
                logger.debug("Request created a session encoded url. Stored session ID {} for that context {}",
                             createdSessionId,
                             contextPath);
            }
        }

    } else {

        String targetPath = sessionStore.get(sessionId);

        if (targetPath == null) {
            targetPath = forwardRoundRobin(baseRequest, response);
            sessionStore.put(sessionId, targetPath);
            logger.debug("Created new target path {} for session {}", targetPath, sessionId);
        } else {
            logger.debug("Applying sticky session pattern for target path {} and session {}",
                         targetPath,
                         sessionId);
            forwardToUrl(targetPath, baseRequest, response);
        }

    }

}
 
Example 18
private void doFilterRequest(HttpServletRequest httpRequest, HttpServletResponse httpResponse, FilterChain chain)
		throws IOException, ServletException {
	if (httpRequest.getHeader(dynLogEnvironment.getDynLogHeaderKey()) != null && dynamicLogLevelProcessor != null) {
		dynamicLogLevelProcessor.copyDynamicLogLevelToMDC(httpRequest);
	}
	/*
	 * -- make sure correlation id is read from headers
	 */
	LogContext.initializeContext(HttpHeaderUtilities.getHeaderValue(httpRequest, HttpHeaders.CORRELATION_ID));

	try {

		RequestRecord rr = requestRecordFactory.create(httpRequest);
		httpRequest.setAttribute(MDC.class.getName(), MDC.getCopyOfContextMap());
		
		if (!httpResponse.isCommitted() && httpResponse.getHeader(HttpHeaders.CORRELATION_ID.getName()) == null) {
			httpResponse.setHeader(HttpHeaders.CORRELATION_ID.getName(), LogContext.getCorrelationId());
		}

		/*
		 * If request logging is disabled skip request instrumentation and continue the
		 * filter chain immediately.
		 */
		if (!RequestLogger.isRequestLoggingEnabled()) {
			doFilter(chain, httpRequest, httpResponse);
			return;
		}

		/*
		 * -- we essentially do three things here: -- a) we create a log
		 * record using our library and log it via STDOUT -- b) keep track
		 * of certain header fields so that they are available in later
		 * processing steps -- b) inject a response wrapper to keep track of
		 * content length (hopefully)
		 */
		if (wrapResponse) {
			httpResponse = new ContentLengthTrackingResponseWrapper(httpResponse);
		}

		if (wrapRequest) {
			httpRequest = new ContentLengthTrackingRequestWrapper(httpRequest);
		}

		RequestLogger loggingVisitor = new RequestLogger(rr, httpRequest, httpResponse);
		httpRequest = new LoggingContextRequestWrapper(httpRequest, loggingVisitor);



		/* -- start measuring right before calling up the filter chain -- */
		rr.start();
		doFilter(chain, httpRequest, httpResponse);

		if (!httpRequest.isAsyncStarted()) {
			loggingVisitor.logRequest();
		}
		/*
		 * -- close this
		 */
	} finally {
		if (dynamicLogLevelProcessor != null) {
			dynamicLogLevelProcessor.removeDynamicLogLevelFromMDC();
		}
		LogContext.resetContextFields();
	}
}
 
Example 19
/**
 * Indicates whether the given request and response are eligible for ETag generation.
 * <p>The default implementation returns {@code true} if all conditions match:
 * <ul>
 * <li>response status codes in the {@code 2xx} series</li>
 * <li>request method is a GET</li>
 * <li>response Cache-Control header is not set or does not contain a "no-store" directive</li>
 * </ul>
 * @param request the HTTP request
 * @param response the HTTP response
 * @param responseStatusCode the HTTP response status code
 * @param inputStream the response body
 * @return {@code true} if eligible for ETag generation, {@code false} otherwise
 */
protected boolean isEligibleForEtag(HttpServletRequest request, HttpServletResponse response,
		int responseStatusCode, InputStream inputStream) {

	String method = request.getMethod();
	if (responseStatusCode >= 200 && responseStatusCode < 300 && HttpMethod.GET.matches(method)) {
		String cacheControl = response.getHeader(HttpHeaders.CACHE_CONTROL);
		return (cacheControl == null || !cacheControl.contains(DIRECTIVE_NO_STORE));
	}
	return false;
}
 
Example 20
Source Project: heimdall   File: CallImpl.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public String get(String name) {
     
     HttpServletResponse r = context.getResponse();
     
     return r.getHeader(name);
}