Java 类org.springframework.web.context.request.RequestContextHolder 实例源码

项目:personspringclouddemo    文件:WebLogAspect.java   
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
    startTime.set(System.currentTimeMillis());

    // 接收到请求,记录请求内容
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    // 记录下请求内容
    logger.info("URL : " + request.getRequestURL().toString());
    logger.info("HTTP_METHOD : " + request.getMethod());
    logger.info("IP : " + request.getRemoteAddr());
    logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
    logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));

}
项目:xm-uaa    文件:DomainConnectionFactoryLocator.java   
@Override
public ConnectionFactory<?> getConnectionFactory(String providerId) {
    HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
        .getRequest();
    String domain = TenantContext.getCurrent().getDomain();
    Optional<SocialConfig> config = socialConfigRepository.findOneByProviderIdAndDomain(providerId, domain);
    if (config.isPresent()) {
        SocialConfig sc = config.get();
        switch (sc.getProviderId()) {
            case "facebook":
                return new FacebookConnectionFactory(sc.getConsumerKey(), sc.getConsumerSecret());
            case "google":
                return new GoogleConnectionFactory(sc.getConsumerKey(), sc.getConsumerSecret());
            case "twitter":
                return new TwitterConnectionFactory(sc.getConsumerKey(), sc.getConsumerSecret());
            case "linkedin":
                return new LinkedInConnectionFactory(sc.getConsumerKey(), sc.getConsumerSecret());
            default:
                break;
        }
    }
    throw new IllegalArgumentException("No provider config found for " + providerId);
}
项目:Spring-5.0-Cookbook    文件:DeleteAuthorizeAspect.java   
@Around("classPointcut() && delPointcut()  && @annotation(mapping)")
public String delEmployee(ProceedingJoinPoint joinPoint,  RequestMapping mapping) throws Throwable{
       HttpServletRequest req = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
       logger.info("executing " + joinPoint.getSignature().getName());
       int userId = (Integer)req.getSession().getAttribute("userId");
       System.out.println("userId" + userId);

       List<RolePermission> permission = loginServiceImpl.getPermissionSets(userId);
       if(isAuthroize(permission)){
           logger.info("user " + userId + " is authroied to delete");
           joinPoint.proceed();
           return "menu";
       }else{
           logger.info("user " + userId + " is NOT authroied to delete");
           return "banned";
       }
}
项目:pinkyLam-Blog-Server    文件:WebLogAspect.java   
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
    startTime.set(System.currentTimeMillis());

    // 接收到请求,记录请求内容
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    // 记录下请求内容
    logger.info("请求地址 : " + request.getRequestURL().toString());
    logger.info("请求方法类型 : " + request.getMethod());
    logger.info("IP : " + request.getRemoteAddr());
    logger.info("请求方法 : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
    logger.info("参数 : " + Arrays.toString(joinPoint.getArgs()));

}
项目:bnade-web-ssh    文件:StatisticAspect.java   
/**
 * 查询物品最低价时统计物品查询
 * @param point 切点
 * @return 切面方法返回值
 * @throws Throwable 异常
 */
@Around("execution(public * com.bnade.wow.controller.CheapestAuctionController.findAll(..))")
public Object process(ProceedingJoinPoint point) throws Throwable {
    // 获取方法参数
    CheapestAuction cheapestAuction = null;
    Object[] args = point.getArgs();
    if (args != null && args.length == 1) {
        cheapestAuction = (CheapestAuction)args[0];
    }
    // 实际方法运行
    Object returnValue = point.proceed();
    if (cheapestAuction != null && returnValue != null && returnValue instanceof List) {
        // 当有返回数据时才统计
        if (((List) returnValue).size() > 0) {
            // 获取httprequest
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            String ip = IPUtils.getIp(request);
            // 统计物品搜索
            logger.debug("记录ip: {}, item: {}", ip, cheapestAuction.getItemId());
            statisticService.recordItemSearchedByIp(ip, "" + cheapestAuction.getItemId());
        }
    }
    return returnValue;
}
项目:sporticus    文件:RestControllerAdminUser.java   
/**
 * Function to read all users
 *
 * @return ResponseEntity<DtoUsers>
 */
@RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<DtoList<DtoUser>> readAll() {
    if (!this.getLoggedInUser().isAdmin()) {
        LOGGER.error(() -> "Users can only be read by system administrators");
        return new ResponseEntity<>(HttpStatus.FORBIDDEN);
    }

    if(false) {
        ServletRequestAttributes attr = (ServletRequestAttributes)
                RequestContextHolder.currentRequestAttributes();
        HttpSession session = attr.getRequest().getSession(true); // true == allow create
    }

    /**
     * As well as the standard user data we want to include statistics for number of users and groups
     * (as well as number of open invitations)
     */
    final DtoList list = new DtoList<DtoUser>();
    this.serviceUser.getAll().forEach(u -> {
        list.add(getDtoUser(u));
    });
    return new ResponseEntity<>(list, HttpStatus.OK);
}
项目:dooo    文件:HeadPrinter.java   
public static void printHead(Model model) {
   HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    UserAuthDO userAuthDO = UserAuth.getCurrentUser(httpServletRequest);
    if (userAuthDO != null) {
        model.addAttribute("user", userAuthDO);
    }
}
项目:Your-Microservice    文件:YourServletUriComponentsBuilder.java   
/**
 * Obtain the request through {@link RequestContextHolder}.
 * @return the active servlet request
 */
protected static HttpServletRequest getCurrentRequest() {
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    Assert.state(requestAttributes != null, "Could not find current request via RequestContextHolder");
    Assert.isInstanceOf(ServletRequestAttributes.class, requestAttributes);
    HttpServletRequest servletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
    Assert.state(servletRequest != null, "Could not find current HttpServletRequest");
    return servletRequest;
}
项目:happylifeplat-tcc    文件:SpringCloudTxTransactionInterceptor.java   
@Override
public Object interceptor(ProceedingJoinPoint pjp) throws Throwable {
    TccTransactionContext tccTransactionContext;
    //如果不是本地反射调用补偿
    RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
    HttpServletRequest request = requestAttributes == null ? null : ((ServletRequestAttributes) requestAttributes).getRequest();
    String context = request == null ? null : request.getHeader(CommonConstant.TCC_TRANSACTION_CONTEXT);
    tccTransactionContext =
            GsonUtils.getInstance().fromJson(context, TccTransactionContext.class);

    return tccTransactionAspectService.invoke(tccTransactionContext, pjp);
}
项目:juiser    文件:RequestContextUser.java   
protected User findUser() {
    try {
        RequestAttributes reqAttr = RequestContextHolder.currentRequestAttributes();

        if (reqAttr instanceof ServletRequestAttributes) {

            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) reqAttr;

            HttpServletRequest request = servletRequestAttributes.getRequest();

            if (request != null) {
                Object obj = request.getAttribute(User.class.getName());
                if (obj instanceof User) {
                    return (User) obj;
                }
            }
        }
    } catch (IllegalStateException e) {
        log.debug("Unable to obtain request context user via RequestContextHolder.", e);
    }

    return null;
}
项目:SpringBoot_Wechat_Sell    文件:SellerAuthorizeAspect.java   
@Before("verify()")
public void doVerify() {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    //查询cookie
    Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);
    if (cookie == null) {
        log.warn("【登录校验】Cookie中查不到token");
        throw new SellerAuthorizeException();
    }

    //去redis里查询
    String tokenValue = redisTemplate.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX, cookie.getValue()));
    if (StringUtils.isEmpty(tokenValue)) {
        log.warn("【登录校验】Redis中查不到token");
        throw new SellerAuthorizeException();
    }
}
项目:myth    文件:SpringCloudMythTransactionInterceptor.java   
@Override
public Object interceptor(ProceedingJoinPoint pjp) throws Throwable {
    MythTransactionContext mythTransactionContext = TransactionContextLocal.getInstance().get();
    if (Objects.nonNull(mythTransactionContext) &&
            mythTransactionContext.getRole() == MythRoleEnum.LOCAL.getCode()) {
        mythTransactionContext = TransactionContextLocal.getInstance().get();
    } else {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = requestAttributes == null ? null : ((ServletRequestAttributes) requestAttributes).getRequest();
        String context = request == null ? null : request.getHeader(CommonConstant.MYTH_TRANSACTION_CONTEXT);
        if (StringUtils.isNoneBlank(context)) {
            mythTransactionContext =
                    GsonUtils.getInstance().fromJson(context, MythTransactionContext.class);
        }
    }
    return mythTransactionAspectService.invoke(mythTransactionContext, pjp);
}
项目:admin-shiro    文件:AdminCtl.java   
@RequiresPermissions("admin:index")
@ResponseBody
@RequestMapping(value = "/admins", method = RequestMethod.GET)
public ResponseDTO list() {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    Integer pageSize = Integer.valueOf(Objects.nonNull(request.getParameter("pageSize")) ? request.getParameter("pageSize") : "20");
    Integer pageNumber = Integer.valueOf(Objects.nonNull(request.getParameter("pageIndex")) ? request.getParameter("pageIndex") : "1");
    String userName = request.getParameter("userName");
    String email = request.getParameter("email");
    String reservation = request.getParameter("reservation");
    logger.info("查询条件为,userName:{},email:{},reservation:{}", userName, email, reservation);
    Map<String, Object> params = new HashMap();
    if (!StringUtils.isEmpty(userName)) {
        params.put("userName", userName);
    }
    if (!StringUtils.isEmpty(email)) {
        params.put("userEmail", email);
    }
    Pagination<AdminDO> pagination = adminService.pageAdminsByConditions(pageNumber, pageSize, params);
    return new ResponseDTO(0, "success", pagination);
}
项目:spring-boot-aop    文件:RequestLogAspect.java   
@Around("@annotation(org.springframework.web.bind.annotation.RequestMapping) && execution(public * *(..))")
public Object log(final ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes())
            .getRequest();

    Object value;

    try {
        value = proceedingJoinPoint.proceed();
    } catch (Throwable throwable) {
        throw throwable;
    } finally {
        log.info(
                "{} {} from {}",
                request.getMethod(),
                request.getRequestURI(),
                request.getRemoteAddr(),
                request.getHeader("user-id"));
    }

    return value;
}
项目:spring-boot-aop    文件:RestrictAspect.java   
@Before("@annotation(com.nibado.example.springaop.aspects.Restrict) && execution(public * *(..))")
public void restrict(final JoinPoint joinPoint) throws Throwable {
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Restrict annotation = signature.getMethod().getAnnotation(Restrict.class);

    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes())
            .getRequest();

    if (annotation.admin() && !isAdmin(request)) {
        throw new ForbiddenException("Need admin access");
    }

    if (annotation.localOnly()
            && !request.getRemoteAddr().equals("127.0.0.1")
            && !request.getRemoteAddr().equals("0:0:0:0:0:0:0:1")) {
        throw new ForbiddenException("Only possible from localhost");
    }
}
项目:xmanager    文件:BaseController.java   
/**
 * 下载
 * @param file 文件
 * @param fileName 生成的文件名
 * @return {ResponseEntity}
 */
protected ResponseEntity<Resource> download(File file, String fileName) {
    Resource resource = new FileSystemResource(file);

    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
            .getRequestAttributes()).getRequest();
    String header = request.getHeader("User-Agent");
    // 避免空指针
    header = header == null ? "" : header.toUpperCase();
    HttpStatus status;
    if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
        fileName = URLUtils.encodeURL(fileName, Charsets.UTF_8);
        status = HttpStatus.OK;
    } else {
        fileName = new String(fileName.getBytes(Charsets.UTF_8), Charsets.ISO_8859_1);
        status = HttpStatus.CREATED;
    }
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    headers.setContentDispositionFormData("attachment", fileName);
    return new ResponseEntity<Resource>(resource, headers, status);
}
项目:xmanager    文件:BaseController.java   
/**
 * 下载
 * @param file 文件
 * @param fileName 生成的文件名
 * @return {ResponseEntity}
 */
protected ResponseEntity<Resource> download(File file, String fileName) {
    Resource resource = new FileSystemResource(file);

    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
            .getRequestAttributes()).getRequest();
    String header = request.getHeader("User-Agent");
    // 避免空指针
    header = header == null ? "" : header.toUpperCase();
    HttpStatus status;
    if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
        fileName = URLUtils.encodeURL(fileName, Charsets.UTF_8);
        status = HttpStatus.OK;
    } else {
        fileName = new String(fileName.getBytes(Charsets.UTF_8), Charsets.ISO_8859_1);
        status = HttpStatus.CREATED;
    }
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    headers.setContentDispositionFormData("attachment", fileName);
    return new ResponseEntity<Resource>(resource, headers, status);
}
项目:sso    文件:ThirdPartyLoginAspect.java   
@Before("loginHandle()")
public void doBefore(JoinPoint pjp) throws Throwable {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    Principal principal = request.getUserPrincipal();
    if (principal != null && principal instanceof Pac4jPrincipal) {
        logger.debug("准备判断用户绑定状态");
        Pac4jPrincipal pac4jPrincipal = (Pac4jPrincipal) principal;

        //获取认证客户端
        String clientName = (String) pac4jPrincipal.getProfile().getAttribute("clientName");
        //获取客户端策略
        ClientStrategy clientStrategy = clientStrategyFactory.getClientStrategy().get(clientName);
        if (clientStrategy != null) {

            //判断该客户端是否已经有绑定用户
            if (!clientStrategy.isBind(pac4jPrincipal)) {
                logger.debug("用户[" + pac4jPrincipal.getProfile().getId() + "]通过" + clientStrategy.name() + "登录尚未绑定");
                //未绑定给予处理
                clientStrategy.handle(pjp, pac4jPrincipal);
            }
        }
    }
}
项目:tac-ms-starter-parent    文件:WebLogAop.java   
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws ParamException, JsonProcessingException {
    startTime.set(System.currentTimeMillis());

    // 接收到请求,记录请求内容
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    // 记录下请求内容
    logger.info("URL : " + request.getRequestURL().toString());
    logger.info("HTTP_METHOD : " + request.getMethod());
    logger.info("IP : " + request.getRemoteAddr());
    logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
    if (joinPoint.getArgs().length == 2 ) {
        logger.info("ARGS : " + JsonUtil.toJson(joinPoint.getArgs()[0]));
    }

}
项目:Burst    文件:WebLogAspect.java   
@Before("webLog()")
public void doBefore(JoinPoint joinPoint){
    log.info("------------日志开始:"+LocalDateTime.now()+"------------");
    startTime.set(System.currentTimeMillis());
    // 接收到请求,记录请求内容
    log.info("WebLogAspect.doBefore()");
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    // 记录下请求内容
    log.info("URL : " + request.getRequestURL().toString());
    log.info("HTTP_METHOD : " + request.getMethod());
    log.info("IP : " + request.getRemoteAddr());
    log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
    log.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
    //获取所有参数方法一:
    Enumeration enu=request.getParameterNames();
    while(enu.hasMoreElements()){
        String paraName=(String)enu.nextElement();
        log.info("PARAM :"+"("+paraName+" : "+request.getParameter(paraName)+")");
    }
}
项目:VersioningWithEnvers    文件:UserNameFilter.java   
@Override
public void filter(ContainerRequestContext ctx) throws IOException {

    MultivaluedMap<String, String> headers = ctx.getHeaders();

    if(headers == null) {
        handleError(ctx);
    }

    if(!headers.containsKey("X-Username")) {
        handleError(ctx);
    }

    String username = headers.getFirst("X-Username");

    if(username == null) {
        handleError(ctx);
    }

    // Set the Username in the current Request Scope:
    RequestContextHolder
            .currentRequestAttributes()
            .setAttribute("Username", username, SCOPE_REQUEST);
}
项目:FCat    文件:LogAspect.java   
@Before("log()")
public void before(JoinPoint joinPoint) {
    timeTreadLocal.set(System.currentTimeMillis());
    // 接收到请求,记录请求内容
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    //获取请求的request
    HttpServletRequest request = attributes.getRequest();
    //获取所有请求的参数,封装为map对象
    // Map<String,Object> parameterMap = getParameterMap(request);
    MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    //获取被拦截的方法
    Method method = methodSignature.getMethod();
    //获取被拦截的方法名
    String methodName = method.getName();
    logger.info("AOP begin ,请求开始方法  :{}", method.getDeclaringClass() + "." + methodName + "()");
    //获取所有请求参数key和value
    String keyValue = getReqParameter(request);
    logger.info("请求url = {}", request.getRequestURL().toString());
    logger.info("请求方法requestMethod = {}", request.getMethod());
    logger.info("请求资源uri = {}", request.getRequestURI());
    logger.info("所有的请求参数 key:value = {}", keyValue);
}
项目:springboot-start    文件:WebLogAspect.java   
@Before(value = "webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());
        // 接收到请求,记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
//        log.info("URL : " + request.getRequestURL().toString());
//        log.info("HTTP_METHOD : " + request.getMethod());
//        log.info("IP : " + request.getRemoteAddr());
//        log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
//        log.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
//        BasicDBObject logInfo = ;
        l.set(getBasicDBObject(request, joinPoint));
//        log.info(logInfo);
    }
项目:happylifeplat-transaction    文件:SpringCloudTxTransactionInterceptor.java   
@Override
public Object interceptor(ProceedingJoinPoint pjp) throws Throwable {
    final String compensationId = CompensationLocal.getInstance().getCompensationId();
    String groupId = null;
    if (StringUtils.isBlank(compensationId)) {
        //如果不是本地反射调用补偿
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = requestAttributes == null ? null : ((ServletRequestAttributes) requestAttributes).getRequest();
        groupId = request == null ? null : request.getHeader(CommonConstant.TX_TRANSACTION_GROUP);
    }

    return aspectTransactionService.invoke(groupId, pjp);
}
项目:short-url    文件:ControllerLogAspect.java   
@Before("requestRecord()")
public void record() {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    String ip = request.getHeader("X-Real-IP");
    String path = request.getServletPath();
    logger.info("{} access {}", ip, path);
}
项目:SensitiveWordFilter    文件:LogAspect.java   
private void writeLog(String detailErrMsg, JoinPoint joinPoint, Exception ex) {

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.
                getRequestAttributes()).getRequest();
        // 获取请求的URL
        StringBuffer requestURL = request.getRequestURL();
        // 获取参数信息
        String queryString = request.getQueryString();
        // 封装完整请求URL带参数
        if(queryString != null){
            requestURL.append("?").append(queryString);
        }

        String cla = joinPoint.getTarget().getClass().getName();//action
        String method = joinPoint.getSignature().getName();//method
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat sdf_simple = new SimpleDateFormat("yyyy-MM-dd");
            // 创建输出异常log日志
            File dir = new File("");
            File file = new File(dir.getAbsolutePath() + "/" + sdf_simple.format(new Date()) + "-" + "exception.log");
            if (!file.exists()) {
                file.createNewFile();
            }

            FileOutputStream out = new FileOutputStream(file,true); //如果追加方式用true
            //日志具体参数
            StringBuffer sb = new StringBuffer();
            sb.append("-----------" + sdf.format(new Date()) + "------------\r\n");
            sb.append("请求URL:[" + requestURL + "]\r\n");
            sb.append("对应API:[" + cla + "." + method + "]\r\n");
            sb.append("错误MSG:" + ex + "\r\n");
            sb.append(detailErrMsg + "\r\n");
            out.write(sb.toString().getBytes("utf-8"));//注意需要转换对应的字符集
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
项目:outcomes    文件:LogAspect.java   
@Before("weblog()")
public void doBefore(JoinPoint joinpoint) throws Throwable {
    ServletRequestAttributes attributes =
            (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    log.info("URL : " + request.getRequestURL().toString());
    log.info("TYPE : " + request.getMethod());
    log.info("REMOTE IP : " + request.getRemoteAddr());
    log.info("METHOD : " + joinpoint.getSignature().getDeclaringTypeName() + "." + joinpoint.getSignature().getName());
    log.info("PARAMETERS : " + Arrays.toString(joinpoint.getArgs()));
}
项目:Spring-5.0-Cookbook    文件:LoginAuthAspect.java   
@Before("classPointcut() && loginSubmitPointcut()  && @annotation(mapping)")
public void registerParams(JoinPoint joinPoint,  RequestMapping mapping) throws ServletException, IOException{
       HttpServletRequest req = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
       logger.info("executing " + joinPoint.getSignature().getName());
       String loginRequestMethod = mapping.method()[0].name();
       logger.info("executing " + joinPoint.getSignature().getName() + " which is a " + loginRequestMethod + " request");
       if(loginRequestMethod.equalsIgnoreCase("POST")){
           String username =  req.getParameter("username");
           String password =  req.getParameter("password");
          logger.warn("MVC application detected access from user: " + username + " with password: " + password );
       }
}
项目:springboot-shiro-cas-mybatis    文件:AbstractCasExpirationPolicy.java   
/**
 * Gets the http request based on the
 * {@link org.springframework.web.context.request.RequestContextHolder}.
 * @return the request or null
 */
protected final HttpServletRequest getRequest() {
    try {
        final ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        if (attrs != null) {
            return attrs.getRequest();
        }
    }  catch (final Exception e) {
        LOGGER.trace("Unable to obtain the http request", e);
    }
    return null;
}
项目:Spring-Boot-Server    文件:AppDepartmentRestful.java   
/**
 * 科室信息
 * @return
 */
@RequestMapping(value = "/list")
@ResponseBody
public PageData getDepartmentlist() throws Exception {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    String HE_AREA = request.getParameter("HE_AREA");
    PageData pd = this.getPageData();
    pd.put("HE_AREA", HE_AREA);
    List<PageData> accInfo = appDepartmentMapper.getDeptList(pd);
    return WebResult.requestSuccess(accInfo);
}
项目:framework    文件:Servlets.java   
/**
 * 获取当前请求对象
 *
 * @return
 */
public static HttpServletRequest getRequest() {
    try {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    } catch (Exception e) {
        return null;
    }
}
项目:framework    文件:StringUtils.java   
/**
 * 获得i18n字符串
 */
public static String getMessage(String code, Object[] args) {
    LocaleResolver localLocaleResolver = (LocaleResolver) SpringContextHolder.getBean(LocaleResolver.class);
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    Locale localLocale = localLocaleResolver.resolveLocale(request);
    return SpringContextHolder.getApplicationContext().getMessage(code, args, localLocale);
}
项目:cas-5.1.0    文件:WebUtils.java   
/**
 * Gets http servlet request from request attributes.
 *
 * @return the http servlet request from request attributes
 */
public static HttpServletRequest getHttpServletRequestFromRequestAttributes() {
    try {
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    } catch (final Exception e) {
        LOGGER.trace(e.getMessage(), e);
    }
    return null;
}
项目:NEILREN4J    文件:StringUtils.java   
/**
 * 获得i18n字符串
 */
public static String getMessage(String code, Object[] args) {
    LocaleResolver localLocaleResolver = (LocaleResolver) SpringContextHolder.getBean(LocaleResolver.class);
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    Locale localLocale = localLocaleResolver.resolveLocale(request);
    return SpringContextHolder.getApplicationContext().getMessage(code, args, localLocale);
}
项目:My-Blog    文件:LogAspect.java   
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
    // 接收到请求,记录请求内容
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    // 记录下请求内容
    LOGGER.info("URL : " + request.getRequestURL().toString() + ",IP : " + request.getRemoteAddr() + ",CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() + ",ARGS : " + Arrays.toString(joinPoint.getArgs()));
}
项目:sucok-framework    文件:WebUtils.java   
public static HttpServletRequest getCurrentRequest() {
    ServletRequestAttributes reqAttrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    if (reqAttrs == null) {
        return null;
    }
    HttpServletRequest request = reqAttrs.getRequest();
    return request;
}
项目:lib-edge    文件:BeforeControllerAdvice.java   
@Around("init()")
public Object filterAroundHandling(ProceedingJoinPoint joinPoint) throws Throwable {
  log.debug("around handing");
  //action
  MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
  Method action = methodSignature.getMethod();
  //接收到请求,记录请求内容
  ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  HttpServletRequest request = attributes.getRequest();
  //流控
  String clientIp = request.getRemoteAddr();
  String sessionId = request.getSession().getId();
  String requestUri = request.getRequestURI();
  String requestMethod = request.getMethod();
  long requestTimestamp = System.currentTimeMillis();
  flowControlService.flowController(clientIp, sessionId, requestUri, requestMethod, requestTimestamp, action.getDeclaredAnnotation(FlowControl.class));
  //过滤参数
  Map<String, String[]> filterParam = filterParamService.filterParam(request.getParameterMap(), action.getDeclaredAnnotation(FilterParam.class));
  //触发action, 完成参数校验部分
  Object object = joinPoint.proceed();
  log.debug("local response: {}", object);
  //透传
  PipeConfig pipeConfig = action.getAnnotation(PipeConfig.class);
  if (pipeConfig != null) {
    object = penetrationService.penetrate(request, action, methodSignature.getDeclaringType(), filterParam);
  }
  log.debug("penetration response: {}", object);
  return object;
}
项目:tx-lcn    文件:TxManagerInterceptor.java   
public Object around(ProceedingJoinPoint point) throws Throwable {

        TxTransactionCompensate compensate = TxTransactionCompensate.current();
        String groupId = null;
        int maxTimeOut = 0;
        if (compensate == null) {
            try {
                RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
                HttpServletRequest request = requestAttributes == null ? null : ((ServletRequestAttributes) requestAttributes).getRequest();
                groupId = request == null ? null : request.getHeader("tx-group");
                maxTimeOut = request == null?0:Integer.parseInt(request.getHeader("tx-maxTimeOut"));
            }catch (Exception e){}
        }
        return aspectBeforeService.around(groupId,maxTimeOut, point);
    }
项目:webDemo    文件:CustomerUserDetailService.java   
public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    Integer accountType = Integer.valueOf(request.getParameter(SecurityUtil.ACCOUNT_TYPE));
    CustomerUserDetail customerUserDetail = securityService.getUserDetailByName(name, accountType);
    if (customerUserDetail == null) {
        throw new UsernameNotFoundException("用户不存在或密码错误");
    }
    return customerUserDetail;
}
项目:dooo    文件:SecurityAspect.java   
public Object execute(ProceedingJoinPoint pjp) throws Throwable {
    HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    HttpServletResponse httpServletResponse = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    UserAuthDO userAuthDO = UserAuth.getCurrentUser(httpServletRequest);
    if (userAuthDO == null) {
        return ReturnT.FAIL;
    }
    // 调用目标方法
    return pjp.proceed();
}