javax.servlet.http.HttpServletRequest#getHeader()源码实例Demo

下面列出了javax.servlet.http.HttpServletRequest#getHeader() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: cruise-control   文件: UserTaskManager.java
/**
 * Method returns the user task id based on the {@link HttpServletRequest}. This method tries to find
 * the User-Task-ID from the request header and check if there is any UserTask with the same User-Task-ID.
 * If no User-Task-ID is passed then the {@link HttpSession} is used to fetch the User-Task-ID.
 *
 * @param httpServletRequest the HttpServletRequest to fetch the User-Task-ID and HTTPSession.
 * @return UUID of the user tasks or null if user task doesn't exist.
 */
public UUID getUserTaskId(HttpServletRequest httpServletRequest) {
  String userTaskIdString = httpServletRequest.getHeader(USER_TASK_HEADER_NAME);

  UUID userTaskId;
  if (userTaskIdString != null && !userTaskIdString.isEmpty()) { // valid user task id
    userTaskId = UUID.fromString(userTaskIdString);
  } else {
    SessionKey sessionKey = new SessionKey(httpServletRequest);
    synchronized (_sessionKeyToUserTaskIdMap) {
      userTaskId = _sessionKeyToUserTaskIdMap.get(sessionKey);
    }
  }

  return userTaskId;
}
 
源代码2 项目: sakai   文件: SpreadsheetUtil.java
/**
 * Convenience method for setting the content-disposition:attachment header with escaping a file name.
 * @param response
 * @param fileName unescaped file name of the attachment
 */
protected static void setEscapedAttachmentHeader(final HttpServletResponse response, final String fileName) {
	String escapedFilename;
	try {
		escapedFilename = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
	} catch (UnsupportedEncodingException e) {
		escapedFilename = fileName;
	}

	FacesContext faces = FacesContext.getCurrentInstance();
	HttpServletRequest request = (HttpServletRequest) faces.getExternalContext().getRequest();
	String userAgent = request.getHeader("User-Agent");
	if (userAgent != null && userAgent.contains("MSIE")) {
		response.setHeader("Content-Disposition", "attachment" +
				((!StringUtils.isEmpty(escapedFilename)) ? ("; filename=\"" + escapedFilename + "\"") : ""));
	} else {
		response.setHeader("Content-Disposition", "attachment" +
				((!StringUtils.isEmpty(escapedFilename)) ? ("; filename*=utf-8''" + escapedFilename) : ""));
	}
}
 
源代码3 项目: microservice-recruit   文件: FeignConfig.java
@Bean
public RequestInterceptor headerInterceptor() {
    // 传递header
    return requestTemplate -> {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            Enumeration<String> headerNames = request.getHeaderNames();
            if (headerNames != null) {
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();
                    String values = request.getHeader(name);
                    requestTemplate.header(name, values);
                }
            }
        }
    };
}
 
@Override
public String getToken() {
	HttpServletRequest request = httpRequest.getIfAvailable();
	if (request == null) {
		throw new IllegalStateException("No HttpServletRequest available");
	}

	String token = request.getHeader(ConfigClientProperties.TOKEN_HEADER);
	if (!StringUtils.hasLength(token)) {
		throw new IllegalArgumentException(
				"Missing required header in HttpServletRequest: "
						+ ConfigClientProperties.TOKEN_HEADER);
	}

	return token;
}
 
源代码5 项目: hauth-java   文件: JwtService.java
public static Authentication getAuthentication(HttpServletRequest request) {

        // 从Header中拿到token
        String token = request.getHeader(HEADER_STRING);
        if (token == null) {
            token = getTokenFromCookis(request);
        }

        if (token != null && !token.isEmpty()) {
            // 解析 Token
            Claims claims = Jwts.parser().setSigningKey(SECRET)
                    .parseClaimsJws(token).getBody();

            // 获取用户名
            String user = claims.get("UserId").toString();

            // 获取权限(角色)
            List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList((String) claims.get("authorities"));

            // 返回验证令牌
            return user != null ? new UsernamePasswordAuthenticationToken(user, null, authorities) : null;
        }
        return null;
    }
 
源代码6 项目: sakai   文件: JwtAuthenticationTokenFilter.java
/**
 * Attempt to authenticate request - basically just pass over to another method to authenticate request headers
 */
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {

    String header = request.getHeader(tokenHeader);
    if (header == null || !header.startsWith("Bearer ")) {
        throw new JwtTokenMissingException("No JWT token found in request headers");
    }
    String authToken = header.substring(7);

    if (SecurityContextHolder.getContext().getAuthentication() == null) {
        JwtAuthenticationToken authentication = new JwtAuthenticationToken(authToken);
        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }
    return SecurityContextHolder.getContext().getAuthentication();
}
 
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String state = xsrfUtils.newToken();
    request.getSession().setAttribute(XsrfUtils.XSRF_KEY, state);

    // todo https://developers.google.com/accounts/docs/OpenIDConnect#discovery
    String location = "https://accounts.google.com/o/oauth2/auth"
            + "?client_id=" + appConfig.getGoogleClientId()
            + "&response_type=code"
            + "&scope=openid%20email"
            + "&redirect_uri=" + request.getHeader("Referer") + "auth/google/response"
            + "&state=" + state;

    response.sendRedirect(location);
}
 
源代码8 项目: development   文件: IPResolver.java
public static String resolveIpAddress(HttpServletRequest request) {
    Enumeration<?> headerNames = request.getHeaderNames();
    if (headerNames != null) {
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            if (headerName.equalsIgnoreCase("x-forwarded-for")) {
                String ipAddress = request.getHeader(headerName);
                if (ipAddress != null && ipAddress.trim().length() > 0) {
                    return ipAddress;
                }
            }
        }
    }
    return request.getRemoteAddr();
}
 
源代码9 项目: orion.server   文件: GenericFileHandler.java
/**
 * Handles If-Match header precondition
 *
 * @param request The HTTP request object
 * @param response The servlet response object
 * @param etag The file's ETag
 * @return {@code true} if the If-Match header precondition failed (doesn't match the file's ETag), {@code false} otherwise
 */
protected boolean handleIfMatchHeader(HttpServletRequest request, HttpServletResponse response, String etag) {
	String ifMatchHeader = request.getHeader(ProtocolConstants.HEADER_IF_MATCH);
	if (ifMatchHeader != null && !ifMatchHeader.equals(etag)) {
		response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
		return true;
	}
	return false;
}
 
源代码10 项目: nomulus   文件: RequestParameters.java
/**
 * Returns first HTTP header associated with {@code name}.
 *
 * @param name case insensitive header name
 * @throws BadRequestException if request header is absent or empty
 */
public static String extractRequiredHeader(HttpServletRequest req, String name) {
  String result = req.getHeader(name);
  if (isNullOrEmpty(result)) {
    throw new BadRequestException("Missing header: " + name);
  }
  return result;
}
 
源代码11 项目: SpringAll   文件: MyAuthenticationSucessHandler.java
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
    // 1. 从请求头中获取 ClientId
    String header = request.getHeader("Authorization");
    if (header == null || !header.startsWith("Basic ")) {
        throw new UnapprovedClientAuthenticationException("请求头中无client信息");
    }

    String[] tokens = this.extractAndDecodeHeader(header, request);
    String clientId = tokens[0];
    String clientSecret = tokens[1];

    TokenRequest tokenRequest = null;

    // 2. 通过 ClientDetailsService 获取 ClientDetails
    ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);

    // 3. 校验 ClientId和 ClientSecret的正确性
    if (clientDetails == null) {
        throw new UnapprovedClientAuthenticationException("clientId:" + clientId + "对应的信息不存在");
    } else if (!passwordEncoder.matches(clientSecret, clientDetails.getClientSecret())) {
        throw new UnapprovedClientAuthenticationException("clientSecret不正确");
    } else {
        // 4. 通过 TokenRequest构造器生成 TokenRequest
        tokenRequest = new TokenRequest(new HashMap<>(), clientId, clientDetails.getScope(), "custom");
    }

    // 5. 通过 TokenRequest的 createOAuth2Request方法获取 OAuth2Request
    OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
    // 6. 通过 Authentication和 OAuth2Request构造出 OAuth2Authentication
    OAuth2Authentication auth2Authentication = new OAuth2Authentication(oAuth2Request, authentication);

    // 7. 通过 AuthorizationServerTokenServices 生成 OAuth2AccessToken
    OAuth2AccessToken token = authorizationServerTokenServices.createAccessToken(auth2Authentication);

    // 8. 返回 Token
    log.info("登录成功");
    response.setContentType("application/json;charset=UTF-8");
    response.getWriter().write(new ObjectMapper().writeValueAsString(token));
}
 
源代码12 项目: star-zone   文件: MomentController.java
@PostMapping("/like")
public ResponseData like(HttpServletRequest request, long momentId) {
    String userIdStr = request.getHeader("userId");
    log.info("MomentController.like__momentId={},userIdStr={}", new Object[]{momentId, userIdStr});
    momentLikeService.like(momentId, Long.valueOf(userIdStr));
    return ResponseData.newOK();
}
 
private String getJwtFromRequest(HttpServletRequest request){
    String bearerToken = request.getHeader("Authorization");
    if(StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")){
        return bearerToken.substring(7, bearerToken.length());
    }
    return null;
}
 
源代码14 项目: anyline   文件: WebUtil.java
/**
 * 判断是否是ajax请求
 *
 * @param request  request
 * @return return
 */
public static boolean isAjaxRequest(HttpServletRequest request) {
	String header = request.getHeader("x-requested-with");
	if (header != null && "XMLHttpRequest".equals(header)) {
		return true;
	}
	return false;
}
 
private String tokenFromRequest(HttpServletRequest request) {
    final String value = request.getHeader("Authorization");

    if (value == null || !value.toLowerCase().startsWith("bearer")) {
        return null;
    }

    String[] parts = value.split(" ");

    if (parts.length < 2) {
        return null;
    }

    return parts[1].trim();
}
 
private static String getCallerIp(HttpServletRequest req) {
  String ip = req.getRemoteAddr();
  // Make sure to get the actual IP of the requester if
  // the service works behind a gateway.
  String forward = req.getHeader("X-Forwarded-For");
  if (forward != null) {
    ip = forward;
  }
  return ip;
}
 
源代码17 项目: newblog   文件: IPUtils.java
public static String getIpAddr(HttpServletRequest request) {
    String ip = request.getHeader("x-forwarded-for");
    if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
        // 多次反向代理后会有多个ip值,第一个ip才是真实ip
        if (ip.indexOf(",") != -1) {
            ip = ip.split(",")[0];
        }
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("HTTP_CLIENT_IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("HTTP_X_FORWARDED_FOR");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("X-Real-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getRemoteAddr();
    }
    return ip;
}
 
源代码18 项目: engine   文件: HeaderSiteResolver.java
@Override
public String getSiteName(HttpServletRequest request) {
    String siteName = request.getHeader(headerName);
    if (StringUtils.isEmpty(siteName)) {
        logger.debug("No '{}' request header found", headerName);
    }

    return siteName;
}
 
源代码19 项目: vespa   文件: HttpRequestDispatch.java
private static RequestHandler wrapHandlerIfFormPost(RequestHandler requestHandler,
                                                    HttpServletRequest servletRequest,
                                                    boolean removeBodyForFormPost) {
    if (!servletRequest.getMethod().equals("POST")) {
        return requestHandler;
    }
    String contentType = servletRequest.getHeader(HttpHeaders.Names.CONTENT_TYPE);
    if (contentType == null) {
        return requestHandler;
    }
    if (!contentType.startsWith(APPLICATION_X_WWW_FORM_URLENCODED)) {
        return requestHandler;
    }
    return new FormPostRequestHandler(requestHandler, getCharsetName(contentType), removeBodyForFormPost);
}
 
源代码20 项目: star-zone   文件: MomentController.java
@PostMapping("/delete")
public ResponseData delete(HttpServletRequest request, long id) {
    String userIdStr = request.getHeader("userId");
    momentService.delete(id, Long.valueOf(userIdStr));
    return ResponseData.newOK();
}