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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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();
}