Java Code Examples for org.springframework.web.context.request.RequestContextHolder#getRequestAttributes()
The following examples show how to use
org.springframework.web.context.request.RequestContextHolder#getRequestAttributes() .
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: FeignHeadConfig.java From parker with MIT License | 6 votes |
@Bean public RequestInterceptor requestInterceptor() { return requestTemplate -> { ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (attrs != null) { HttpServletRequest request = attrs.getRequest(); Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames != null) { while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); String value = request.getHeader(name); // 遍历请求头里面的属性字段,将token添加到新的请求头中转发到下游服务 if ("token".equalsIgnoreCase(name)) { //log.debug("添加自定义请求头key:" + name + ",value:" + value); requestTemplate.header(name, value); } } } else { log.warn("FeignHeadConfig", "获取请求头失败!"); } } }; }
Example 2
Source File: FeignRequestInterceptor.java From mall-swarm with Apache License 2.0 | 6 votes |
@Override public void apply(RequestTemplate 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); } } } }
Example 3
Source File: UserSession.java From framework with Apache License 2.0 | 6 votes |
public static UserSession getUserSession() { ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest req = requestAttributes.getRequest(); AdamProperties adamProperties = CHERRY.SPRING_CONTEXT.getBean(AdamProperties.class); String jwtToken = req.getHeader(adamProperties.getSecurity().getJwtToken().getHeaderName()); if (StringUtils.isBlank(jwtToken)) { jwtToken = req.getParameter(adamProperties.getSecurity().getJwtToken().getRequestName()); } jwtToken = jwtToken.replace(adamProperties.getSecurity().getJwtToken().getPrefix() + " ", ""); UserSession userSession = new UserSession(); if (StringUtils.isNotBlank(jwtToken)) { String userSessionString = CHERRY.SPRING_CONTEXT.getBean(StringRedisTemplate.class).boundValueOps(CHERRY.REDIS_KEY_SESSION + jwtToken).get(); userSession = JSON.parseObject(userSessionString, UserSession.class); } return userSession; }
Example 4
Source File: WebLogAspect.java From spring-boot-study with MIT License | 6 votes |
/** * 指定当前执行方法在logPointCut之前执行 * */ @Before("logPointCut()") public void doBefore(JoinPoint joinPoint) throws Throwable{ // 接收到请求,记录请求内容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 记录下请求内容 logger.info("请求地址 : " + request.getRequestURL().toString()); logger.info("HTTP METHOD : " + request.getMethod()); // 获取真实的ip地址 //logger.info("IP : " + IPAddressUtil.getClientIpAddress(request)); logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); logger.info("参数 : " + Arrays.toString(joinPoint.getArgs())); //loggger.info("参数 : " + joinPoint.getArgs()); }
Example 5
Source File: RequestHolder.java From mogu_blog_v2 with Apache License 2.0 | 5 votes |
/** * 获取所有session key * * @return String[] */ public static String[] getSessionKeys() { log.debug("getSessionKeys -- Thread id :{}, name : {}", Thread.currentThread().getId(), Thread.currentThread().getName()); ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()); if (null == servletRequestAttributes) { return null; } return servletRequestAttributes.getAttributeNames(RequestAttributes.SCOPE_SESSION); }
Example 6
Source File: WebLogAspect.java From mall-learning with Apache License 2.0 | 5 votes |
@Around("webLog()") public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable { long startTime = System.currentTimeMillis(); //获取当前请求对象 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); //记录请求信息 WebLog webLog = new WebLog(); Object result = joinPoint.proceed(); Signature signature = joinPoint.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod(); if (method.isAnnotationPresent(ApiOperation.class)) { ApiOperation apiOperation = method.getAnnotation(ApiOperation.class); webLog.setDescription(apiOperation.value()); } long endTime = System.currentTimeMillis(); String urlStr = request.getRequestURL().toString(); webLog.setBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath())); webLog.setIp(request.getRemoteUser()); webLog.setMethod(request.getMethod()); webLog.setParameter(getParameter(method, joinPoint.getArgs())); webLog.setResult(result); webLog.setSpendTime((int) (endTime - startTime)); webLog.setStartTime(startTime); webLog.setUri(request.getRequestURI()); webLog.setUrl(request.getRequestURL().toString()); // LOGGER.info("{}", JSONUtil.parse(webLog)); Map<String,Object> logMap = new HashMap<>(); logMap.put("url",webLog.getUrl()); logMap.put("method",webLog.getMethod()); logMap.put("parameter",webLog.getParameter()); logMap.put("spendTime",webLog.getSpendTime()); logMap.put("description",webLog.getDescription()); LOGGER.info(Markers.appendEntries(logMap), JSONUtil.parse(webLog).toString()); return result; }
Example 7
Source File: LoginRestApi.java From mogu_blog_v2 with Apache License 2.0 | 5 votes |
@ApiOperation(value = "退出登录", notes = "退出登录", response = String.class) @PostMapping(value = "/logout") public String logout() { ServletRequestAttributes attribute = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attribute.getRequest(); String token = request.getAttribute(SysConf.TOKEN).toString(); redisUtil.delete(RedisConf.LOGIN_TOKEN_KEY + RedisConf.SEGMENTATION + token); return ResultUtil.result(SysConf.SUCCESS, MessageConf.OPERATION_SUCCESS); }
Example 8
Source File: FeignHttpInterceptorConfig.java From microservices-platform with Apache License 2.0 | 5 votes |
/** * 使用feign client访问别的微服务时,将上游传过来的access_token、username、roles等信息放入header传递给下一个服务 */ @Bean public RequestInterceptor httpFeignInterceptor() { return template -> { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder .getRequestAttributes(); if (attributes != null) { HttpServletRequest request = attributes.getRequest(); Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames != null) { String headerName; String headerValue; while(headerNames.hasMoreElements()) { headerName = headerNames.nextElement(); if (requestHeaders.contains(headerName)) { headerValue = request.getHeader(headerName); template.header(headerName, headerValue); } } } //传递access_token,无网络隔离时需要传递 /* String token = extractHeaderToken(request); if (StrUtil.isEmpty(token)) { token = request.getParameter(CommonConstant.ACCESS_TOKEN); } if (StrUtil.isNotEmpty(token)) { template.header(CommonConstant.TOKEN_HEADER, CommonConstant.BEARER_TYPE + " " + token); } */ } }; }
Example 9
Source File: BaseController.java From feiqu-opensource with Apache License 2.0 | 5 votes |
protected FqUserCache getCurrentUser(){ ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes) RequestContextHolder .getRequestAttributes()); HttpServletRequest request = servletRequestAttributes .getRequest(); HttpServletResponse response = servletRequestAttributes .getResponse(); WebUtil webUtil = SpringUtils.getBean(WebUtil.class); return webUtil.currentUser(request,response); }
Example 10
Source File: LogAspect.java From uccn with Apache License 2.0 | 5 votes |
@Before("logPointCut()") public void doBefore(JoinPoint joinPoint) throws Throwable { // 接收到请求,记录请求内容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); Map<String, String[]> parameterMap = request.getParameterMap(); // 记录下请求内容 logger.info("请求地址 : " + request.getRequestURL().toString()); logger.info("HTTP METHOD : " + request.getMethod()); logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); logger.info("参数 : " + Arrays.toString(joinPoint.getArgs())); logger.info("参数 : " + joinPoint.getArgs()); logger.info("请求参数 : " + JSONUtil.toJsonStr(parameterMap)); }
Example 11
Source File: UmsAdminServiceImpl.java From macrozheng with Apache License 2.0 | 5 votes |
/** * 添加登录记录 * @param username 用户名 */ private void insertLoginLog(String username) { UmsAdmin admin = getAdminByUsername(username); UmsAdminLoginLog loginLog = new UmsAdminLoginLog(); loginLog.setAdminId(admin.getId()); loginLog.setCreateTime(new Date()); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); loginLog.setIp(request.getRemoteAddr()); loginLogMapper.insert(loginLog); }
Example 12
Source File: CookieUtils.java From NetworkDisk_Storage with GNU General Public License v2.0 | 4 votes |
public static void saveCookie(Cookie cookie) { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletResponse response = attributes.getResponse(); response.addCookie(cookie); }
Example 13
Source File: WxMenuController.java From black-shop with Apache License 2.0 | 4 votes |
@GetMapping("/create") public String menuCreateSample(@PathVariable String appid) throws WxErrorException, MalformedURLException { WxMenu menu = new WxMenu(); WxMenuButton button1 = new WxMenuButton(); button1.setType(MenuButtonType.CLICK); button1.setName("今日歌曲"); button1.setKey("V1001_TODAY_MUSIC"); // WxMenuButton button2 = new WxMenuButton(); // button2.setType(WxConsts.BUTTON_MINIPROGRAM); // button2.setName("小程序"); // button2.setAppId("wx286b93c14bbf93aa"); // button2.setPagePath("pages/lunar/index.html"); // button2.setUrl("http://mp.weixin.qq.com"); WxMenuButton button3 = new WxMenuButton(); button3.setName("菜单"); menu.getButtons().add(button1); // menu.getButtons().add(button2); menu.getButtons().add(button3); WxMenuButton button31 = new WxMenuButton(); button31.setType(MenuButtonType.VIEW); button31.setName("搜索"); button31.setUrl("http://www.soso.com/"); WxMenuButton button32 = new WxMenuButton(); button32.setType(MenuButtonType.VIEW); button32.setName("视频"); button32.setUrl("http://v.qq.com/"); WxMenuButton button33 = new WxMenuButton(); button33.setType(MenuButtonType.CLICK); button33.setName("赞一下我们"); button33.setKey("V1001_GOOD"); WxMenuButton button34 = new WxMenuButton(); button34.setType(MenuButtonType.VIEW); button34.setName("获取用户信息"); ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder .getRequestAttributes(); if (servletRequestAttributes != null) { HttpServletRequest request = servletRequestAttributes.getRequest(); URL requestURL = new URL(request.getRequestURL().toString()); String url = WxMpConfiguration.getMpServices() .get(appid).oauth2buildAuthorizationUrl(String.format("%s://%s/wx/redirect/%s/greet", requestURL.getProtocol(), requestURL.getHost(), appid), WxConsts.OAuth2Scope.SNSAPI_USERINFO, null); button34.setUrl(url); } button3.getSubButtons().add(button31); button3.getSubButtons().add(button32); button3.getSubButtons().add(button33); button3.getSubButtons().add(button34); return WxMpConfiguration.getMpServices().get(appid).getMenuService().menuCreate(menu); }
Example 14
Source File: WebRequestLogAspect.java From oauth2-server with MIT License | 4 votes |
/** * 接收到请求,记录请求内容 * * @param joinPoint * @throws Throwable */ @Before("wsLog()") public void doBefore(JoinPoint joinPoint) throws Throwable { if (log.isInfoEnabled()) { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (attributes != null) { HttpServletRequest request = attributes.getRequest(); Map<String, String[]> parameters = request.getParameterMap(); try { String parametersString = null; String requestBody = null; if (parameters != null) { parametersString = JsonUtil.multiValueMapToJsonString(parameters); } MethodSignature signature = (MethodSignature) joinPoint.getSignature(); //获取被拦截的方法 Method method = signature.getMethod(); Object object = getAnnotatedParameterValueRequestBody(method, joinPoint.getArgs()); if (object != null) { requestBody = JsonUtil.objectToJsonString(object); } StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append("\nRequest from = "); stringBuffer.append(ClientIpUtil.getIpAddress(request)); stringBuffer.append(";\n"); stringBuffer.append("uri = "); stringBuffer.append(request.getRequestURL().toString()); stringBuffer.append(";\n"); stringBuffer.append("request method = "); stringBuffer.append(request.getMethod()); stringBuffer.append(";\n"); stringBuffer.append("content type = "); stringBuffer.append(request.getContentType()); stringBuffer.append(";\n"); stringBuffer.append("request parameters = "); stringBuffer.append(parametersString); stringBuffer.append(";\n"); stringBuffer.append("request body = "); stringBuffer.append(requestBody); stringBuffer.append(";\n"); log.info(stringBuffer.toString()); String headers = JsonUtil.objectToJsonString(getHeadersInfo(request)); log.info("headers:" + headers); } catch (Exception e) { log.info("log http request Exception: ", e); } } } }
Example 15
Source File: ServletUtils.java From DimpleBlog with Apache License 2.0 | 4 votes |
public static ServletRequestAttributes getRequestAttributes() { RequestAttributes attributes = RequestContextHolder.getRequestAttributes(); return (ServletRequestAttributes) attributes; }
Example 16
Source File: CookieUtil.java From uccn with Apache License 2.0 | 4 votes |
public static Cookie[] getCookies() { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); Cookie[] c = request.getCookies(); return c; }
Example 17
Source File: RequestContext.java From EserKnife with Apache License 2.0 | 4 votes |
public static HttpServletRequest getRequest(){ ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); return requestAttributes==null? null : requestAttributes.getRequest(); }
Example 18
Source File: WebRequestLogAspect.java From oauth2-resource with MIT License | 4 votes |
@Before("wsLog()") public void doBefore(JoinPoint joinPoint) { // 接收到请求,记录请求内容 if (log.isInfoEnabled()) { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (attributes != null) { HttpServletRequest request = attributes.getRequest(); // 记录下请求内容 Map<String, String[]> parameters = request.getParameterMap(); try { String parametersString = null; String requestBody = null; if (parameters != null) { parametersString = JsonUtil.multiValueMapToJsonString(parameters); } MethodSignature signature = (MethodSignature) joinPoint.getSignature(); //获取被拦截的方法 Method method = signature.getMethod(); Object object = getAnnotatedParameterValueRequestBody(method, joinPoint.getArgs()); if (object != null) { requestBody = JsonUtil.objectToJsonString(object); } StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append("\n"); Principal principal = request.getUserPrincipal(); if (principal != null) { stringBuffer.append("Request user "); stringBuffer.append(principal.getName()); stringBuffer.append(";\n"); } stringBuffer.append("Request from "); stringBuffer.append(ClientIpUtils.getIpAddress(request)); stringBuffer.append(";\n"); stringBuffer.append("User-Agent = "); stringBuffer.append(request.getHeader("User-Agent")); stringBuffer.append(";\n"); stringBuffer.append("uri = "); stringBuffer.append(request.getRequestURL().toString()); stringBuffer.append(";\n"); stringBuffer.append("request method = "); stringBuffer.append(request.getMethod()); stringBuffer.append(";\n"); stringBuffer.append("request parameters = "); stringBuffer.append(parametersString); stringBuffer.append(";\n"); stringBuffer.append("request body = "); stringBuffer.append(requestBody); stringBuffer.append(";\n"); log.info(stringBuffer.toString()); } catch (Exception e) { log.error("log http request Exception: ", e); } } } }
Example 19
Source File: CookieUtil.java From uccn with Apache License 2.0 | 4 votes |
public static void saveCookie(Cookie cookie) { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletResponse response = attributes.getResponse(); response.addCookie(cookie); }
Example 20
Source File: ServletUtils.java From yue-library with Apache License 2.0 | 2 votes |
/** * 获得当前请求上下文中的{@linkplain ServletRequestAttributes} * @return ServletRequestAttributes */ public static ServletRequestAttributes getRequestAttributes() { return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()); }