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

项目: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()));

}
项目:linux-memory-monitor    文件:CallbackMappingJackson2HttpMessageConverter.java   
@Override   //Object就是springmvc返回值
protected void writeInternal(Object object, HttpOutputMessage outputMessage) throws IOException,
        HttpMessageNotWritableException {
    // 从threadLocal中获取当前的Request对象
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
            .currentRequestAttributes()).getRequest();

    String callbackParam = request.getParameter(callbackName);
    if (StringUtils.isEmpty(callbackParam)) {
        // 没有找到callback参数,直接返回json数据
        super.writeInternal(object, outputMessage);
    } else {
        JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
        try {
            //将对象转换为json串,然后用回调方法包括起来
            String result = callbackParam + "(" + super.getObjectMapper().writeValueAsString(object)
                    + ");";
            IOUtils.write(result, outputMessage.getBody(), encoding.getJavaName());
        } catch (JsonProcessingException ex) {
            throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex);
        }
    }

}
项目: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;
}
项目: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);
            }
        }
    }
}
项目: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";
       }
}
项目:LazyREST    文件:SecurityAspect.java   
/**
 * 接收到客户端请求时执行
 *
 * @param pjp
 * @return
 * @throws Throwable
 */
@Around("controllerAspect()")
public Object execute(ProceedingJoinPoint pjp) throws Throwable {
    // 从切点上获取目标方法
    MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
    Method method = methodSignature.getMethod();
    /**
     * 验证Token
     */
    if (method.isAnnotationPresent(Token.class)) {
        // 从 request header 中获取当前 token
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader(DEFAULT_TOKEN_NAME);
        if (StringUtils.isEmpty(token)) {
            throw new TokenException("客户端X-Token参数不能为空,且从Header中传入,如果没有登录,请先登录获取Token");
        }
        // 检查 token 有效性
        if (!tokenManager.checkToken(token)) {
            String message = String.format("Token [%s] 非法", token);
            throw new TokenException(message);
        }
    }

    // 调用目标方法
    return pjp.proceed();
}
项目:lib-edge    文件:BeforeControllerAdvice.java   
@Before("init()")
public void filterBeforeHandling(JoinPoint joinPoint) throws Exception {
  log.debug("before handing");
  ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  HttpServletRequest request = attributes.getRequest();
  Map<String, String> requestInfoMap = new LinkedHashMap<>();
  String clientIpAddr = RequestHelper.getRealIp(request);
  String requestUri = request.getRequestURI();
  String requestMethod = request.getMethod();
  int size = 0;
  requestInfoMap.put(TemplateEnum.MESSAGE_SOURCE, environment.getProperty(ENV_LOG_KAFKA_MESSAGE_SOURCE));
  requestInfoMap.put(TemplateEnum.REMOTE_HOST, clientIpAddr);
  requestInfoMap.put(TemplateEnum.REQUEST_METHOD, requestMethod);
  requestInfoMap.put(TemplateEnum.RESPONSE_BODY_SIZE, String.valueOf(size));
  requestInfoMap.put(TemplateEnum.REQUEST_URI, requestUri);
  requestInfoMap.put(TemplateEnum.SERVICE_NAME, environment.getProperty(ENV_APPLICATION_NAME));
  requestInfo.set(requestInfoMap);
  startTime.set(System.currentTimeMillis());
}
项目: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);
    }
}
项目: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);
}
项目:cas-server-4.2.1    文件: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;
}
项目: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);
}
项目:lams    文件:RequestContextFilter.java   
@Override
protected void doFilterInternal(
        HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {

    ServletRequestAttributes attributes = new ServletRequestAttributes(request);
    initContextHolders(request, attributes);

    try {
        filterChain.doFilter(request, response);
    }
    finally {
        resetContextHolders();
        if (logger.isDebugEnabled()) {
            logger.debug("Cleared thread-bound request context: " + request);
        }
        attributes.requestCompleted();
    }
}
项目:oneops    文件:DataAccessAspect.java   
@Around("@annotation(ReadOnlyDataAccess)")
public Object accessDataReadOnly(ProceedingJoinPoint joinPoint) throws Throwable {
  HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
  String dataConsistency = request.getHeader(HEADER_DATA_CONSISTENCY);
  Object returnValue;
  if (isQueryStandByEnabled && "weak".equals(dataConsistency)) {
    if (logger.isDebugEnabled()) {
      logger.debug("marking " + joinPoint.getSignature().getName() + " read only ");
    }
    DataTypeHolder.setReadOnlyData();
    try {
      returnValue = joinPoint.proceed();
    } catch (Throwable throwable) {
      DataTypeHolder.clear();
      logger.info("retrying the request " + joinPoint.getSignature().getName() + " in primary");
      returnValue = joinPoint.proceed();
    } finally {
      DataTypeHolder.clear();
    }
    return returnValue;
  }
  return joinPoint.proceed();
}
项目: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;
}
项目: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);
    }
项目:ProxyPool    文件:WebLogAspect.java   
@Before("log()")
public void doBeforeController(JoinPoint joinPoint) {

    // 接收到请求,记录请求内容
    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<String> enu = request.getParameterNames();
    while (enu.hasMoreElements()) {
        String paraName = (String) enu.nextElement();
        System.out.println(paraName + ": " + request.getParameter(paraName));
    }
}
项目: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)+")");
    }
}
项目: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();
}
项目:easyweb    文件:Servlets.java   
/**
 * 获取当前请求对象
 * @return
 */
public static HttpServletRequest getRequest(){
    try{
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }catch(Exception e){
        return null;
    }
}
项目:Plum    文件:ApiLogAspect.java   
@Before("api()")
private void doBefore(JoinPoint joinPoint){

    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    Map<String, Object> requestAsMap = getRequestAsMap(request);

    log.info("classMethod:{},arguments:{}",joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName(),
            Arrays.toString(joinPoint.getArgs()));
    log.info("Request:"+requestAsMap.toString());

}
项目: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;
}
项目:knowledge-forest-dialogue-recommendation    文件:WxErrorController.java   
private Map<String, Object> getErrorAttributes(HttpServletRequest request,
                                               boolean includeStackTrace) {
    RequestAttributes requestAttributes = new ServletRequestAttributes(
            request);
    Map<String, Object> map = this.errorAttributes
            .getErrorAttributes(requestAttributes, includeStackTrace);
    logger.error("map is [{}]", map);
    String url = request.getRequestURL().toString();
    map.put("URL", url);
    logger.error("[error info]: status-{}, request url-{}",
            map.get("status"), url);
    return map;
}
项目: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;
}
项目:easyweb    文件: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);
}
项目: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()));
}
项目:FastBootWeixin    文件:WxWebUtils.java   
public static WxMessageParameter getWxMessageParameter() {
    WxRequest wxRequest = getWxRequestFromRequest();
    if (wxRequest != null) {
        return new WxRequestMessageParameter(wxRequest);
    }
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes != null && requestAttributes instanceof ServletRequestAttributes) {
        return new HttpRequestMessageParameter(((ServletRequestAttributes) requestAttributes).getRequest());
    }
    return new HttpRequestMessageParameter(null);
}
项目: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();
        }
    }
项目:sucok-framework    文件:WebUtils.java   
public static HttpServletRequest getCurrentRequest() {
    ServletRequestAttributes reqAttrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    if (reqAttrs == null) {
        return null;
    }
    HttpServletRequest request = reqAttrs.getRequest();
    return request;
}
项目: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);
    }
项目: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;
}
项目: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;
}
项目:webDemo    文件:WebLogAspect.java   
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
    logger.debug("***************请求开始***************");
    // 接收到请求,记录请求内容
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    CommLogger commLogger = new CommLogger();
    commLogger.setActionUrlAll(request.getRequestURL().toString());
    commLogger.setActionUrlTail(request.getServletPath());
    commLogger.setRequestParams(JSON.toJSONString(request.getParameterMap()));
    commLogger.setIp(IPUtil.getRealIP(request));
    commLogger.setReqStartTime(new Date());
    commLoggerThreadLocal.set(commLogger);

    // 记录下请求内容
    logger.debug("URL : " + request.getRequestURL().toString());
    logger.debug("HTTP_METHOD : " + request.getMethod());
    logger.debug("IP : " + IPUtil.getRealIP(request));
    logger.debug("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
    logger.debug("ARGS : " + Arrays.toString(joinPoint.getArgs()));
    logger.debug("params : " + JSON.toJSONString(request.getParameterMap()));

}
项目:istio-ola    文件:OlaController.java   
@CrossOrigin
@RequestMapping(method = RequestMethod.GET, value = "/logout", produces = "text/plain")
@ApiOperation("Logout")
public String logout() throws ServletException {
  HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
  request.logout();
  return "Logged out";
}
项目:fish-admin    文件:WebLogAspectConfig.java   
@Before("weblog()")
public void doBefore(JoinPoint joinpoint) throws Throwable {
    // 接收到请求,记录请求内容
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    // 记录下请求内容
    logger.info("Started " + request.getMethod() + " "
            + request.getRequestURL().toString() + " for "
            + request.getRemoteAddr() + " at " + LocalDateTime.now());
    logger.info("Processing by " + joinpoint.getSignature().getDeclaringTypeName() + "." + joinpoint.getSignature().getName()
            + " " + request.getContentType());
    logger.info("Parameters: " + mapper.writeValueAsString(request.getParameterMap()));
}
项目: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()));
}