org.springframework.web.context.request.RequestContextHolder Java Examples
The following examples show how to use
org.springframework.web.context.request.RequestContextHolder.
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: WebLogAspect.java From dk-foundation with GNU Lesser General Public License v2.1 | 6 votes |
@Before("webLog()") public void doBefore(JoinPoint joinPoint) throws Throwable { // 接收到请求,记录请求内容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (attributes == null) { return; } HttpServletRequest request = attributes.getRequest(); // 记录下请求内容 logger.info("URL : " + request.getRemoteAddr() + ":" + request.getMethod() + "->" + request.getRequestURL().toString()); logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs())); }
Example #2
Source File: GrayFeignRequestInterceptor.java From lion with Apache License 2.0 | 6 votes |
@Override public void apply(RequestTemplate template) { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 设置请求头header信息 Enumeration<String> headerNames = request.getHeaderNames(); if (null != headerNames) { while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); String value = request.getHeader(name); // 若version版本号为空,则赋值默认版本号 if (name.equals(GrayConstant.VERSION) && StringUtils.isEmpty(value)) { value = GrayConstant.DEFAULT_VERSION; } template.header(name, value); } } // 设置灰度版本 String version = request.getHeader(GrayConstant.VERSION); RibbonFilterContextHolder.getCurrentContext().add(GrayConstant.VERSION, version); }
Example #3
Source File: ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void testRequestScopeWithProxiedInterfaces() { RequestContextHolder.setRequestAttributes(oldRequestAttributes); ApplicationContext context = createContext(ScopedProxyMode.INTERFACES); IScopedTestBean bean = (IScopedTestBean) context.getBean("request"); // should be dynamic proxy, implementing both interfaces assertTrue(AopUtils.isJdkDynamicProxy(bean)); assertTrue(bean instanceof AnotherScopeTestInterface); assertEquals(DEFAULT_NAME, bean.getName()); bean.setName(MODIFIED_NAME); RequestContextHolder.setRequestAttributes(newRequestAttributes); // this is a proxy so it should be reset to default assertEquals(DEFAULT_NAME, bean.getName()); RequestContextHolder.setRequestAttributes(oldRequestAttributes); assertEquals(MODIFIED_NAME, bean.getName()); }
Example #4
Source File: LoginController.java From pulsar-manager with Apache License 2.0 | 6 votes |
@ApiOperation(value = "Logout pulsar manager") @ApiResponses({ @ApiResponse(code = 200, message = "ok"), @ApiResponse(code = 500, message = "Internal server error") }) @RequestMapping(value = "/logout", method = RequestMethod.POST) public ResponseEntity<Map<String, Object>> logout() { Map<String, Object> result = Maps.newHashMap(); HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); String username = request.getHeader("username"); if (userManagementEnable) { usersRepository.findByUserName(username); Optional<UserInfoEntity> userInfoEntityOptional = usersRepository.findByUserName(username); if (!userInfoEntityOptional.isPresent()) { result.put("login", "The user is not exist"); return ResponseEntity.ok(result); } UserInfoEntity userInfoEntity = userInfoEntityOptional.get(); userInfoEntity.setAccessToken(""); usersRepository.update(userInfoEntity); } result.put("logout", "success"); jwtService.removeToken(request.getSession().getId()); return ResponseEntity.ok(result); }
Example #5
Source File: MailinglistController.java From openemm with GNU Affero General Public License v3.0 | 6 votes |
private void loadStatistics(ComAdmin admin, RecipientProgressStatisticDto statistic, MailinglistForm form, ModelMap model) throws Exception { if (statistic == null) { statistic = new RecipientProgressStatisticDto(); } statistic.setMailinglistId(form.getId()); if (statistic.getStartYear() == 0 && statistic.getStartMonth() == 0) { Calendar currentDate = Calendar.getInstance(AgnUtils.getTimeZone(admin)); currentDate.set(Calendar.DAY_OF_MONTH, 1); statistic.setStartYear(currentDate.get(Calendar.YEAR)); statistic.setStartMonth(currentDate.get(Calendar.MONTH)); } String sessionId = RequestContextHolder.getRequestAttributes().getSessionId(); String urlWithoutFormat = birtStatisticsService.getRecipientMonthlyStatisticsUrlWithoutFormat(admin, sessionId, statistic); model.addAttribute(YEAR_LIST, AgnUtils.getYearList(AgnUtils.getStatStartYearForCompany(admin))); model.addAttribute(MONTH_LIST, AgnUtils.getMonthList()); model.addAttribute(BIRT_STATISTIC_URL_WITHOUT_FORMAT, urlWithoutFormat); form.setStatistic(statistic); }
Example #6
Source File: LogAspect.java From microservices-oauth with Apache License 2.0 | 6 votes |
@Around("@annotation(logRequest)") public Object LogRequest(ProceedingJoinPoint joinPoint, LogRequest logRequest) throws Throwable { // Intercepts called class and method name final String className = joinPoint.getSignature().getDeclaringTypeName(); final Logger logger = LoggerFactory.getLogger(className); // Intercepts HTTP/HTTPS request HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); // Logs info logger.info("[{}][{}][{}][{}][{}]", request.getHeader("X-Request-ID"), request.getRemoteHost(), request.getHeader("X-Forwarded-For"), request.getHeader("X-Forwarded-Host"), request.getHeader("X-Forwarded-Proto")); // Allows called method to execute and return it's result, if any return joinPoint.proceed(); }
Example #7
Source File: LogRecordAspect.java From teaching with Apache License 2.0 | 6 votes |
@Around("excudeService()") public Object doAround(ProceedingJoinPoint pjp) throws Throwable { RequestAttributes ra = RequestContextHolder.getRequestAttributes(); ServletRequestAttributes sra = (ServletRequestAttributes) ra; HttpServletRequest request = sra.getRequest(); String url = request.getRequestURL().toString(); String method = request.getMethod(); String uri = request.getRequestURI(); String queryString = request.getQueryString(); logger.info("请求开始, 各个参数, url: {}, method: {}, uri: {}, params: {}", url, method, uri, queryString); // result的值就是被拦截方法的返回值 Object result = pjp.proceed(); logger.info("请求结束,controller的返回值是 " + result); return result; }
Example #8
Source File: PageProcessAspect.java From MicroCommunity with Apache License 2.0 | 6 votes |
@After("dataProcess()") public void after(JoinPoint jp) throws IOException { // 接收到请求,记录请求内容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); PageData pd = request.getAttribute(CommonConstant.CONTEXT_PAGE_DATA) != null ? (PageData) request.getAttribute(CommonConstant.CONTEXT_PAGE_DATA) : null; //保存日志处理 if (pd == null) { return; } //写cookies信息 writeCookieInfo(pd, attributes); }
Example #9
Source File: CustomAuthenticationProvider.java From spring-security with Apache License 2.0 | 6 votes |
/** * 验证用户输入的验证码 * @param inputVerifyCode * @return */ public boolean validateVerifyCode(String inputVerifyCode){ //获取当前线程绑定的request对象 HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); // 这个VerifyCodeFactory.SESSION_KEY是在servlet中存入session的名字 HttpSession session = request.getSession(); String verifyCode = (String)session.getAttribute(VerifyCodeUtil.SESSION_KEY); if(null == verifyCode || verifyCode.isEmpty()){ log.warn("验证码过期请重新验证"); throw new DisabledException("验证码过期,请重新验证"); } // 不分区大小写 verifyCode = verifyCode.toLowerCase(); inputVerifyCode = inputVerifyCode.toLowerCase(); log.info("验证码:{}, 用户输入:{}", verifyCode, inputVerifyCode); return verifyCode.equals(inputVerifyCode); }
Example #10
Source File: ServletTestExecutionListenerTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void legacyWebTestCaseWithoutExistingRequestAttributes() throws Exception { BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(LegacyWebTestCase.class); RequestContextHolder.resetRequestAttributes(); assertRequestAttributesDoNotExist(); listener.beforeTestClass(testContext); listener.prepareTestInstance(testContext); assertRequestAttributesDoNotExist(); verify(testContext, times(0)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE); given(testContext.getAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE)).willReturn(null); listener.beforeTestMethod(testContext); assertRequestAttributesDoNotExist(); verify(testContext, times(0)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE); listener.afterTestMethod(testContext); verify(testContext, times(1)).removeAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE); assertRequestAttributesDoNotExist(); }
Example #11
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 #12
Source File: AbstractGrayHeaderCustomizer.java From summerframework with Apache License 2.0 | 6 votes |
@Override public void apply(R request) { try { ServletRequestAttributes requestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); List<String> headerNames = grayRulesStore.findHeader(registration.getApplicationInfoManager().getInfo().getAppName()); if (headerNames != null) { headerNames.forEach(h -> { String headerKey = h.toLowerCase(); String headerValue = requestAttributes.getRequest().getHeader(h); if (!containsKey(request, headerKey)) { addHeaderToRequest(request, headerKey, headerValue); } }); } } catch (Throwable ex) { logger.error(ex.getMessage(), ex); } }
Example #13
Source File: ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests.java From java-technology-stack with MIT License | 6 votes |
@Test public void testSingletonScopeIgnoresProxyTargetClass() { RequestContextHolder.setRequestAttributes(oldRequestAttributes); ApplicationContext context = createContext(ScopedProxyMode.TARGET_CLASS); ScopedTestBean bean = (ScopedTestBean) context.getBean("singleton"); // should not be a proxy assertFalse(AopUtils.isAopProxy(bean)); assertEquals(DEFAULT_NAME, bean.getName()); bean.setName(MODIFIED_NAME); RequestContextHolder.setRequestAttributes(newRequestAttributes); // not a proxy so this should not have changed assertEquals(MODIFIED_NAME, bean.getName()); // singleton bean, so name should be modified even after lookup ScopedTestBean bean2 = (ScopedTestBean) context.getBean("singleton"); assertEquals(MODIFIED_NAME, bean2.getName()); }
Example #14
Source File: RequestHeaderMethodArgumentResolverTests.java From java-technology-stack with MIT License | 6 votes |
@Before @SuppressWarnings("resource") public void setup() throws Exception { GenericWebApplicationContext context = new GenericWebApplicationContext(); context.refresh(); resolver = new RequestHeaderMethodArgumentResolver(context.getBeanFactory()); Method method = ReflectionUtils.findMethod(getClass(), "params", (Class<?>[]) null); paramNamedDefaultValueStringHeader = new SynthesizingMethodParameter(method, 0); paramNamedValueStringArray = new SynthesizingMethodParameter(method, 1); paramSystemProperty = new SynthesizingMethodParameter(method, 2); paramContextPath = new SynthesizingMethodParameter(method, 3); paramResolvedNameWithExpression = new SynthesizingMethodParameter(method, 4); paramResolvedNameWithPlaceholder = new SynthesizingMethodParameter(method, 5); paramNamedValueMap = new SynthesizingMethodParameter(method, 6); paramDate = new SynthesizingMethodParameter(method, 7); paramInstant = new SynthesizingMethodParameter(method, 8); servletRequest = new MockHttpServletRequest(); webRequest = new ServletWebRequest(servletRequest, new MockHttpServletResponse()); // Expose request to the current thread (for SpEL expressions) RequestContextHolder.setRequestAttributes(webRequest); }
Example #15
Source File: ExpressionValueMethodArgumentResolverTests.java From java-technology-stack with MIT License | 6 votes |
@Before @SuppressWarnings("resource") public void setUp() throws Exception { GenericWebApplicationContext context = new GenericWebApplicationContext(); context.refresh(); resolver = new ExpressionValueMethodArgumentResolver(context.getBeanFactory()); Method method = getClass().getMethod("params", int.class, String.class, String.class); paramSystemProperty = new MethodParameter(method, 0); paramContextPath = new MethodParameter(method, 1); paramNotSupported = new MethodParameter(method, 2); webRequest = new ServletWebRequest(new MockHttpServletRequest(), new MockHttpServletResponse()); // Expose request to the current thread (for SpEL expressions) RequestContextHolder.setRequestAttributes(webRequest); }
Example #16
Source File: ExpressionValueMethodArgumentResolverTests.java From spring-analysis-note with MIT License | 6 votes |
@Before @SuppressWarnings("resource") public void setUp() throws Exception { GenericWebApplicationContext context = new GenericWebApplicationContext(); context.refresh(); resolver = new ExpressionValueMethodArgumentResolver(context.getBeanFactory()); Method method = getClass().getMethod("params", int.class, String.class, String.class); paramSystemProperty = new MethodParameter(method, 0); paramContextPath = new MethodParameter(method, 1); paramNotSupported = new MethodParameter(method, 2); webRequest = new ServletWebRequest(new MockHttpServletRequest(), new MockHttpServletResponse()); // Expose request to the current thread (for SpEL expressions) RequestContextHolder.setRequestAttributes(webRequest); }
Example #17
Source File: ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void testRequestScopeWithProxiedTargetClass() { RequestContextHolder.setRequestAttributes(oldRequestAttributes); ApplicationContext context = createContext(ScopedProxyMode.TARGET_CLASS); IScopedTestBean bean = (IScopedTestBean) context.getBean("request"); // should be a class-based proxy assertTrue(AopUtils.isCglibProxy(bean)); assertTrue(bean instanceof RequestScopedTestBean); assertEquals(DEFAULT_NAME, bean.getName()); bean.setName(MODIFIED_NAME); RequestContextHolder.setRequestAttributes(newRequestAttributes); // this is a proxy so it should be reset to default assertEquals(DEFAULT_NAME, bean.getName()); RequestContextHolder.setRequestAttributes(oldRequestAttributes); assertEquals(MODIFIED_NAME, bean.getName()); }
Example #18
Source File: CustomRequestAttributesRequestContextHolderTests.java From spring-analysis-note with MIT License | 6 votes |
@Before public void setUp() { ServletContext servletContext = new MockServletContext(); MockHttpServletRequest mockRequest = new MockHttpServletRequest(servletContext); mockRequest.setAttribute(FROM_CUSTOM_MOCK, FROM_CUSTOM_MOCK); RequestContextHolder.setRequestAttributes(new ServletWebRequest(mockRequest, new MockHttpServletResponse())); this.wac.setServletContext(servletContext); new AnnotatedBeanDefinitionReader(this.wac).register(WebConfig.class); this.wac.refresh(); this.mockMvc = webAppContextSetup(this.wac) .defaultRequest(get("/").requestAttr(FROM_MVC_TEST_DEFAULT, FROM_MVC_TEST_DEFAULT)) .alwaysExpect(status().isOk()) .build(); }
Example #19
Source File: ServletTestExecutionListenerTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void legacyWebTestCaseWithoutExistingRequestAttributes() throws Exception { BDDMockito.<Class<?>> given(testContext.getTestClass()).willReturn(LegacyWebTestCase.class); RequestContextHolder.resetRequestAttributes(); assertRequestAttributesDoNotExist(); listener.beforeTestClass(testContext); listener.prepareTestInstance(testContext); assertRequestAttributesDoNotExist(); verify(testContext, times(0)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE); given(testContext.getAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE)).willReturn(null); listener.beforeTestMethod(testContext); assertRequestAttributesDoNotExist(); verify(testContext, times(0)).setAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE, Boolean.TRUE); listener.afterTestMethod(testContext); verify(testContext, times(1)).removeAttribute(RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE); assertRequestAttributesDoNotExist(); }
Example #20
Source File: ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void testSingletonScopeIgnoresProxyTargetClass() { RequestContextHolder.setRequestAttributes(oldRequestAttributes); ApplicationContext context = createContext(ScopedProxyMode.TARGET_CLASS); ScopedTestBean bean = (ScopedTestBean) context.getBean("singleton"); // should not be a proxy assertFalse(AopUtils.isAopProxy(bean)); assertEquals(DEFAULT_NAME, bean.getName()); bean.setName(MODIFIED_NAME); RequestContextHolder.setRequestAttributes(newRequestAttributes); // not a proxy so this should not have changed assertEquals(MODIFIED_NAME, bean.getName()); // singleton bean, so name should be modified even after lookup ScopedTestBean bean2 = (ScopedTestBean) context.getBean("singleton"); assertEquals(MODIFIED_NAME, bean2.getName()); }
Example #21
Source File: LimitAspect.java From SpringBootLearn with Apache License 2.0 | 5 votes |
@Around("execution(* com.xd.redislualimit.controller ..*(..) )") public Object interceptor(ProceedingJoinPoint joinPoint) throws Throwable { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); Class<?> targetClass = method.getDeclaringClass(); RateLimit rateLimit = method.getAnnotation(RateLimit.class); if (rateLimit != null) { HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); String ipAddress = IPUtil.getIp(request); String string = ipAddress + "-" + targetClass.getName() + "- " + method.getName() + "-" + rateLimit.key(); List<String> keys = Collections.singletonList(string); Number number = redisTemplate.execute(redisluaScript, keys, rateLimit.count(), rateLimit.time()); if (number != null && number.intValue() != 0 && number.intValue() <= rateLimit.count()) { log.info("限流时间段内访问第:{} 次", number.toString()); return joinPoint.proceed(); } } else { return joinPoint.proceed(); } log.error("已经到设置限流次数"); throw new RuntimeException("已经到设置限流次数"); }
Example #22
Source File: AuthUtils.java From pacbot with Apache License 2.0 | 5 votes |
public static String getClientId(){ final HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); final String authorizationHeaderValue = request.getHeader(HttpHeaders.AUTHORIZATION); final String base64AuthorizationHeader = Optional.ofNullable(authorizationHeaderValue).map(headerValue->headerValue.substring("Basic ".length())).orElse(StringUtils.EMPTY); if(StringUtils.isNotEmpty(base64AuthorizationHeader)){ String decodedAuthorizationHeader = new String(Base64.getDecoder().decode(base64AuthorizationHeader), StandardCharsets.UTF_8); return decodedAuthorizationHeader.split(":")[0]; } return StringUtils.EMPTY; }
Example #23
Source File: SecureUtil.java From magic-starter with GNU Lesser General Public License v3.0 | 5 votes |
/** * 获取request * * @return request */ private HttpServletRequest getRequest() { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); if ((requestAttributes == null)) { throw new SecureException("There is not web environment!"); } return ((ServletRequestAttributes) requestAttributes).getRequest(); }
Example #24
Source File: FeignHystrixConcurrencyStrategy.java From sophia_scaffolding with Apache License 2.0 | 5 votes |
@Override public T call() throws Exception { try { RequestContextHolder.setRequestAttributes(requestAttributes); return target.call(); } finally { RequestContextHolder.resetRequestAttributes(); } }
Example #25
Source File: UserTokenRequiredAspect.java From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License | 5 votes |
@Before("@annotation(userTokenRequired)") public void tokenRequiredWithAnnotation(UserTokenRequired userTokenRequired) throws Throwable{ ServletRequestAttributes reqAttributes = (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes(); HttpServletRequest request = reqAttributes.getRequest(); // checks for token in request header String tokenInHeader = request.getHeader("token"); if(StringUtils.isEmpty(tokenInHeader)){ throw new IllegalArgumentException("Empty token"); } Claims claims = Jwts.parser() .setSigningKey(DatatypeConverter.parseBase64Binary(SecurityServiceImpl.secretKey)) .parseClaimsJws(tokenInHeader).getBody(); if(claims == null || claims.getSubject() == null){ throw new IllegalArgumentException("Token Error : Claim is null"); } String subject = claims.getSubject(); if(subject.split("=").length != 2){ throw new IllegalArgumentException("User token is not authorized"); } }
Example #26
Source File: UserSupplier.java From Gatekeeper with Apache License 2.0 | 5 votes |
/** * Supplies a UserProfile instance representing the currently active user. * * Currently checks if an active HttpServletRequest is available and if so looks up the * UserPrincipal contained there. If the active request does not contain a UserProfile * then an IllegalStateException is thrown. * * If there's no ServletRequestAttribute than throw an IllegalStateException * * @return the currently active UserProfile */ @Override public IGatekeeperUserProfile get() { ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (requestAttributes != null) { HttpServletRequest request = requestAttributes.getRequest(); if (request.getUserPrincipal() == null) { throw new IllegalStateException("Could not determine user on request"); } return (IGatekeeperUserProfile) request.getUserPrincipal(); } throw new IllegalStateException("Could not determine user on request"); }
Example #27
Source File: CometCollectorResponseBodyAdvice.java From Milkomeda with MIT License | 5 votes |
@Override public Object beforeBodyWrite(Object body, @NonNull MethodParameter returnType, @NonNull MediaType selectedContentType, @NonNull Class<? extends HttpMessageConverter<?>> selectedConverterType, @NonNull ServerHttpRequest request, @NonNull ServerHttpResponse response) { RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); if (requestAttributes instanceof ServletRequestAttributes) { ((ServletRequestAttributes) requestAttributes).getRequest().setAttribute(REQUEST_ATTRIBUTE_BODY, body); } return body; }
Example #28
Source File: ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void testSessionScopeWithProxiedTargetClass() { RequestContextHolder.setRequestAttributes(oldRequestAttributesWithSession); ApplicationContext context = createContext(ScopedProxyMode.TARGET_CLASS); IScopedTestBean bean = (IScopedTestBean) context.getBean("session"); // should be a class-based proxy assertTrue(AopUtils.isCglibProxy(bean)); assertTrue(bean instanceof ScopedTestBean); assertTrue(bean instanceof SessionScopedTestBean); assertEquals(DEFAULT_NAME, bean.getName()); bean.setName(MODIFIED_NAME); RequestContextHolder.setRequestAttributes(newRequestAttributesWithSession); // this is a proxy so it should be reset to default assertEquals(DEFAULT_NAME, bean.getName()); bean.setName(MODIFIED_NAME); IScopedTestBean bean2 = (IScopedTestBean) context.getBean("session"); assertEquals(MODIFIED_NAME, bean2.getName()); bean2.setName(DEFAULT_NAME); assertEquals(DEFAULT_NAME, bean.getName()); RequestContextHolder.setRequestAttributes(oldRequestAttributesWithSession); assertEquals(MODIFIED_NAME, bean.getName()); }
Example #29
Source File: SysLogAspect.java From pre with GNU General Public License v3.0 | 5 votes |
/*** * 拦截控制层的操作日志 * @param joinPoint * @return * @throws Throwable */ @Before(value = "sysLogAspect()") public void recordLog(JoinPoint joinPoint) throws Throwable { SysLog sysLog = new SysLog(); //将当前实体保存到threadLocal sysLogThreadLocal.set(sysLog); // 开始时间 long beginTime = Instant.now().toEpochMilli(); HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); PreSecurityUser securityUser = SecurityUtil.getUser(); sysLog.setUserName(securityUser.getUsername()); sysLog.setActionUrl(URLUtil.getPath(request.getRequestURI())); sysLog.setStartTime(LocalDateTime.now()); String ip = ServletUtil.getClientIP(request); sysLog.setIp(ip); sysLog.setLocation(IPUtil.getCityInfo(ip)); sysLog.setRequestMethod(request.getMethod()); String uaStr = request.getHeader("user-agent"); sysLog.setBrowser(UserAgentUtil.parse(uaStr).getBrowser().toString()); sysLog.setOs(UserAgentUtil.parse(uaStr).getOs().toString()); //访问目标方法的参数 可动态改变参数值 Object[] args = joinPoint.getArgs(); //获取执行的方法名 sysLog.setActionMethod(joinPoint.getSignature().getName()); // 类名 sysLog.setClassPath(joinPoint.getTarget().getClass().getName()); sysLog.setActionMethod(joinPoint.getSignature().getName()); sysLog.setFinishTime(LocalDateTime.now()); // 参数 sysLog.setParams(Arrays.toString(args)); sysLog.setDescription(LogUtil.getControllerMethodDescription(joinPoint)); long endTime = Instant.now().toEpochMilli(); sysLog.setConsumingTime(endTime - beginTime); }
Example #30
Source File: RequestHolder.java From mogu_blog_v2 with Apache License 2.0 | 5 votes |
/** * 获取session的Attribute * * @param name session的key * @return Object */ public static Object getSession(String name) { log.debug("getSession -- Thread id :{}, name : {}", Thread.currentThread().getId(), Thread.currentThread().getName()); ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()); if (null == servletRequestAttributes) { return null; } return servletRequestAttributes.getAttribute(name, RequestAttributes.SCOPE_SESSION); }