Java Code Examples for org.springframework.web.context.request.RequestContextHolder

The following are top voted examples for showing how to use org.springframework.web.context.request.RequestContextHolder. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: personspringclouddemo   File: WebLogAspect.java   Source Code and License 10 votes vote down vote up
@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()));

}
 
Example 2
Project: sso   File: ThirdPartyLoginAspect.java   Source Code and License 7 votes vote down vote up
@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);
            }
        }
    }
}
 
Example 3
Project: xm-uaa   File: DomainConnectionFactoryLocator.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 4
Project: Spring-5.0-Cookbook   File: DeleteAuthorizeAspect.java   Source Code and License 6 votes vote down vote up
@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";
	   }
}
 
Example 5
Project: pinkyLam-Blog-Server   File: WebLogAspect.java   Source Code and License 6 votes vote down vote up
@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()));

}
 
Example 6
Project: bnade-web-ssh   File: StatisticAspect.java   Source Code and License 6 votes vote down vote up
/**
 * 查询物品最低价时统计物品查询
 * @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;
}
 
Example 7
Project: sporticus   File: RestControllerAdminUser.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
}
 
Example 8
Project: dooo   File: HeadPrinter.java   Source Code and License 6 votes vote down vote up
public static void printHead(Model model) {
   HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    UserAuthDO userAuthDO = UserAuth.getCurrentUser(httpServletRequest);
    if (userAuthDO != null) {
        model.addAttribute("user", userAuthDO);
    }
}
 
Example 9
Project: Your-Microservice   File: YourServletUriComponentsBuilder.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 10
Project: happylifeplat-tcc   File: SpringCloudTxTransactionInterceptor.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 11
Project: juiser   File: RequestContextUser.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 12
Project: SpringBoot_Wechat_Sell   File: SellerAuthorizeAspect.java   Source Code and License 6 votes vote down vote up
@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();
    }
}
 
Example 13
Project: myth   File: SpringCloudMythTransactionInterceptor.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 14
Project: admin-shiro   File: AdminCtl.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 15
Project: spring-boot-aop   File: RequestLogAspect.java   Source Code and License 6 votes vote down vote up
@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;
}
 
Example 16
Project: spring-boot-aop   File: RestrictAspect.java   Source Code and License 6 votes vote down vote up
@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");
    }
}
 
Example 17
Project: xmanager   File: BaseController.java   Source Code and License 6 votes vote down vote up
/**
 * 下载
 * @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);
}
 
Example 18
Project: xmanager   File: BaseController.java   Source Code and License 6 votes vote down vote up
/**
 * 下载
 * @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);
}
 
Example 19
Project: tac-ms-starter-parent   File: WebLogAop.java   Source Code and License 6 votes vote down vote up
@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]));
    }

}
 
Example 20
Project: Burst   File: WebLogAspect.java   Source Code and License 6 votes vote down vote up
@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)+")");
    }
}
 
Example 21
Project: VersioningWithEnvers   File: UserNameFilter.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 22
Project: FCat   File: LogAspect.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 23
Project: springboot-start   File: WebLogAspect.java   Source Code and License 6 votes vote down vote up
@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);
    }
 
Example 24
Project: happylifeplat-transaction   File: SpringCloudTxTransactionInterceptor.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 25
Project: short-url   File: ControllerLogAspect.java   Source Code and License 5 votes vote down vote up
@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);
}
 
Example 26
Project: SensitiveWordFilter   File: LogAspect.java   Source Code and License 5 votes vote down vote up
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();
        }
    }
 
Example 27
Project: outcomes   File: LogAspect.java   Source Code and License 5 votes vote down vote up
@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()));
}
 
Example 28
Project: Spring-5.0-Cookbook   File: LoginAuthAspect.java   Source Code and License 5 votes vote down vote up
@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 );
	   }
}
 
Example 29
Project: springboot-shiro-cas-mybatis   File: AbstractCasExpirationPolicy.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 30
Project: Spring-Boot-Server   File: AppDepartmentRestful.java   Source Code and License 5 votes vote down vote up
/**
 * 科室信息
 * @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);
}
 
Example 31
Project: framework   File: Servlets.java   Source Code and License 5 votes vote down vote up
/**
 * 获取当前请求对象
 *
 * @return
 */
public static HttpServletRequest getRequest() {
	try {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	} catch (Exception e) {
		return null;
	}
}
 
Example 32
Project: framework   File: StringUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 获得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);
}
 
Example 33
Project: cas-5.1.0   File: WebUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 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;
}
 
Example 34
Project: NEILREN4J   File: StringUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 获得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);
}
 
Example 35
Project: My-Blog   File: LogAspect.java   Source Code and License 5 votes vote down vote up
@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()));
}
 
Example 36
Project: sucok-framework   File: WebUtils.java   Source Code and License 5 votes vote down vote up
public static HttpServletRequest getCurrentRequest() {
	ServletRequestAttributes reqAttrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
	if (reqAttrs == null) {
		return null;
	}
	HttpServletRequest request = reqAttrs.getRequest();
	return request;
}
 
Example 37
Project: lib-edge   File: BeforeControllerAdvice.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 38
Project: tx-lcn   File: TxManagerInterceptor.java   Source Code and License 5 votes vote down vote up
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);
    }
 
Example 39
Project: webDemo   File: CustomerUserDetailService.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 40
Project: dooo   File: SecurityAspect.java   Source Code and License 5 votes vote down vote up
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();
}
 
Example 41
Project: istio-ola   File: OlaController.java   Source Code and License 5 votes vote down vote up
@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";
}
 
Example 42
Project: fish-admin   File: WebLogAspectConfig.java   Source Code and License 5 votes vote down vote up
@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()));
}
 
Example 43
Project: MI-S   File: CustomAuthenticationProvider.java   Source Code and License 5 votes vote down vote up
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authentication;
    String username = token.getName();
    String pwdDigest = token.getCredentials().toString();
    //从数据库找到的用户
    User user = new User();
    if (username != null) {
        user = iUserService.selectByName(username);
    }
    if (user == null) {
        throw new UsernameNotFoundException("用户名不存在或者密码无效");
    }else if (user.getEnabled()==1){
        throw new DisabledException("用户已被禁用");
    }else if(user.getLocked()==1){
        throw new LockedException("账号已被锁定");
    }else if(user.getCredential()==1){
        throw new LockedException("凭证已过期");
    }else if(user.getExpired()==1){
        throw new AccountExpiredException("账号已过期");
    }

    String password = user.getUserPwd();
    //密码可加密处理

    if (!password.equals(pwdDigest)) {
        throw new BadCredentialsException("用户密码错误");
    }
    //与authentication里面的credentials相比较
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    HttpSession session = request.getSession();
    session.setAttribute("user",user);
    //授权
    return new UsernamePasswordAuthenticationToken(user, password, user.getAuthorities());
}
 
Example 44
Project: controller-logger   File: RequestUtil.java   Source Code and License 5 votes vote down vote up
@Nullable
private static HttpServletRequest getCurrentHttpRequest() {
    HttpServletRequest request = null;
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes != null && requestAttributes instanceof ServletRequestAttributes) {
        request = ((ServletRequestAttributes)requestAttributes).getRequest();
    }
    return request;
}
 
Example 45
Project: FastBootWeixin   File: WxWebUtils.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 46
Project: docs-manage   File: WebLogAspect.java   Source Code and License 5 votes vote down vote up
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) {
    startTime.set(System.currentTimeMillis());

    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    logger.info("HTTP_METHOD: {}, URL: {}, IP: {}, CLASS_METHOD: {}, ARGS: {}", request.getMethod(),
            request.getRequestURL().toString(), request.getRemoteAddr(),
            joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName(),
            Arrays.toString(joinPoint.getArgs()));
}
 
Example 47
Project: lams   File: WebApplicationContextUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Return the current RequestAttributes instance as ServletRequestAttributes.
 * @see RequestContextHolder#currentRequestAttributes()
 */
private static ServletRequestAttributes currentRequestAttributes() {
	RequestAttributes requestAttr = RequestContextHolder.currentRequestAttributes();
	if (!(requestAttr instanceof ServletRequestAttributes)) {
		throw new IllegalStateException("Current request is not a servlet request");
	}
	return (ServletRequestAttributes) requestAttr;
}
 
Example 48
Project: lams   File: RequestContextFilter.java   Source Code and License 5 votes vote down vote up
private void initContextHolders(HttpServletRequest request, ServletRequestAttributes requestAttributes) {
	LocaleContextHolder.setLocale(request.getLocale(), this.threadContextInheritable);
	RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable);
	if (logger.isDebugEnabled()) {
		logger.debug("Bound request context to thread: " + request);
	}
}
 
Example 49
Project: itweet-boot   File: WebLogAspect.java   Source Code and License 5 votes vote down vote up
@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()));
}
 
Example 50
Project: admin-shiro   File: RoleCtl.java   Source Code and License 5 votes vote down vote up
@RequestMapping(value = "/menu_tree", method = {RequestMethod.POST, RequestMethod.GET})
@ResponseBody
public ResponseDTO comboTree(@RequestParam String roleId) {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    List<MenuDO> menuList = menuService.listAllMenus();
    List<RoleMenuDO> roleMenuList = roleMenuService.listByRoleId(roleId);
    MenuTreeUtil menuTreeUtil = new MenuTreeUtil(menuList, roleMenuList);
    List<Map<String, Object>> mapList = menuTreeUtil.buildTree();
    ResponseDTO responseDTO = new ResponseDTO(1, "", mapList);
    return responseDTO;
}
 
Example 51
Project: esup-sgc   File: SessionConverter.java   Source Code and License 5 votes vote down vote up
@Override
  public String convert(ILoggingEvent event) {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
HttpSession httpSession = request.getSession(false);
      if (httpSession != null) {
          return httpSession.getId();
      }
      return NO_SESSION;
  }
 
Example 52
Project: SpringBootStudy   File: LogAspect.java   Source Code and License 5 votes vote down vote up
/**
 * 环绕通知 用于拦截Controller层记录用户的操作
 */
@Around("controllerAspect()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {

    logger.info("===> 执行controller - 环绕通知.");
    if(logger.isInfoEnabled()){
        logger.info("===> around: {}", pjp);
    }

    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("===> 请求开始:");
    logger.info("===> 请求参数: url: {}, method: {}, uri: {}, params: {}", url, method, uri, queryString);

    // result的值就是被拦截方法的返回值
    Object result = pjp.proceed();
    ObjectMapper mapper = new ObjectMapper();
    String resutlStr = mapper.writeValueAsString(result);
    logger.info("===> 请求结束:");
    logger.info("===> 请求结束: Controller返回值是:{}", resutlStr);

    return result;
}
 
Example 53
Project: phoenix   File: DataController.java   Source Code and License 5 votes vote down vote up
public 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;
}
 
Example 54
Project: FastBootWeixin   File: WxWebUtils.java   Source Code and License 5 votes vote down vote up
public static WxRequest getWxRequestFromRequest() {
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes != null) {
        return (WxRequest) requestAttributes.getAttribute(WX_REQUEST_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
    }
    return null;
}
 
Example 55
Project: GradePoint   File: GradeQuery.java   Source Code and License 5 votes vote down vote up
/**
 * 绩点查询
 * @param id 学号
 * @return json格式的学生信息以及绩点与成绩信息
 */
@ResponseBody
@RequestMapping(value = "/query")
public Map<String, Object> getGradePoint(@RequestParam(required = false) String id) {
    // 设置响应头部,使客户端可以通过ajax跨域请求该数据
    HttpServletResponse response = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
    response.addHeader("Access-Control-Allow-Origin","*");
    return gradeQueryService.getGradePoint(id);
}
 
Example 56
Project: GradePoint   File: GradeQuery.java   Source Code and License 5 votes vote down vote up
/**
 * 学生姓名学号查询,可模糊匹配
 * @param id 学号
 * @param name 姓名
 * @param page 页号
 * @param size 每页的条目数
 * @return json格式的学生信息数据
 */
@ResponseBody
@RequestMapping(value = "/info")
public Map<String, Object> getStudentInfo(@RequestParam(required = false) String id,
                                          @RequestParam(required = false) String name,
                                          @RequestParam(defaultValue = "1") String page,
                                          @RequestParam(defaultValue = "20") String size) {
    // 设置响应头部,使客户端可以通过ajax跨域请求该数据
    HttpServletResponse response = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
    response.addHeader("Access-Control-Allow-Origin","*");
    return gradeQueryService.getStudentInfo(id, name, page, size);
}
 
Example 57
Project: GradePoint   File: IpQuery.java   Source Code and License 5 votes vote down vote up
/**
 * ip归属地查询
 * @param ip 待查询的ip地址
 * @return json格式的ip地址信息
 */
@ResponseBody
@RequestMapping(value = "/query")
public String getIpInfo(@RequestParam String ip) {
    // 设置响应头部,使客户端可以通过ajax跨域请求该数据
    HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    response.addHeader("Access-Control-Allow-Origin","*");
    response.addHeader("Connection","Keep-Alive");
    response.addHeader("Content-Type","application/json;charset=UTF-8");
    return ipQueryService.getIpInfo(ip);
}
 
Example 58
Project: FastBootWeixin   File: WxWebUtils.java   Source Code and License 5 votes vote down vote up
public static WxWebUser getWxWebUserFromSession() {
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes != null) {
        return (WxWebUser) requestAttributes.getAttribute(WX_SESSION_USER, RequestAttributes.SCOPE_SESSION);
    }
    return null;
}
 
Example 59
Project: WIFIProbe   File: WebLogAspect.java   Source Code and License 5 votes vote down vote up
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
    // Get request
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    // Save request content
    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()));

}
 
Example 60
Project: WIFIProbe   File: WebLogAspect.java   Source Code and License 5 votes vote down vote up
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
    // Get request
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    // Save request content
    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()));

}