當前位置: 首頁>>代碼示例>>Java>>正文


Java ServletRequestAttributes類代碼示例

本文整理匯總了Java中org.springframework.web.context.request.ServletRequestAttributes的典型用法代碼示例。如果您正苦於以下問題:Java ServletRequestAttributes類的具體用法?Java ServletRequestAttributes怎麽用?Java ServletRequestAttributes使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


ServletRequestAttributes類屬於org.springframework.web.context.request包,在下文中一共展示了ServletRequestAttributes類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: doBefore

import org.springframework.web.context.request.ServletRequestAttributes; //導入依賴的package包/類
@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()));

}
 
開發者ID:ju5t1nhhh,項目名稱:personspringclouddemo,代碼行數:17,代碼來源:WebLogAspect.java

示例2: writeInternal

import org.springframework.web.context.request.ServletRequestAttributes; //導入依賴的package包/類
@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);
        }
    }

}
 
開發者ID:jthinking,項目名稱:linux-memory-monitor,代碼行數:25,代碼來源:CallbackMappingJackson2HttpMessageConverter.java

示例3: doBefore

import org.springframework.web.context.request.ServletRequestAttributes; //導入依賴的package包/類
@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);
            }
        }
    }
}
 
開發者ID:kawhii,項目名稱:sso,代碼行數:24,代碼來源:ThirdPartyLoginAspect.java

示例4: findUser

import org.springframework.web.context.request.ServletRequestAttributes; //導入依賴的package包/類
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;
}
 
開發者ID:juiser,項目名稱:juiser,代碼行數:24,代碼來源:RequestContextUser.java

示例5: delPointcut

import org.springframework.web.context.request.ServletRequestAttributes; //導入依賴的package包/類
@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";
	   }
}
 
開發者ID:PacktPublishing,項目名稱:Spring-5.0-Cookbook,代碼行數:18,代碼來源:DeleteAuthorizeAspect.java

示例6: execute

import org.springframework.web.context.request.ServletRequestAttributes; //導入依賴的package包/類
/**
 * 接收到客戶端請求時執行
 *
 * @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();
}
 
開發者ID:melonlee,項目名稱:LazyREST,代碼行數:33,代碼來源:SecurityAspect.java

示例7: filterBeforeHandling

import org.springframework.web.context.request.ServletRequestAttributes; //導入依賴的package包/類
@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());
}
 
開發者ID:chuangxian,項目名稱:lib-edge,代碼行數:20,代碼來源:BeforeControllerAdvice.java

示例8: printHead

import org.springframework.web.context.request.ServletRequestAttributes; //導入依賴的package包/類
public static void printHead(Model model) {
   HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    UserAuthDO userAuthDO = UserAuth.getCurrentUser(httpServletRequest);
    if (userAuthDO != null) {
        model.addAttribute("user", userAuthDO);
    }
}
 
開發者ID:wxz1211,項目名稱:dooo,代碼行數:8,代碼來源:HeadPrinter.java

示例9: interceptor

import org.springframework.web.context.request.ServletRequestAttributes; //導入依賴的package包/類
@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);
}
 
開發者ID:yu199195,項目名稱:happylifeplat-tcc,代碼行數:13,代碼來源:SpringCloudTxTransactionInterceptor.java

示例10: getRequest

import org.springframework.web.context.request.ServletRequestAttributes; //導入依賴的package包/類
/**
 * 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;
}
 
開發者ID:yuweijun,項目名稱:cas-server-4.2.1,代碼行數:17,代碼來源:AbstractCasExpirationPolicy.java

示例11: interceptor

import org.springframework.web.context.request.ServletRequestAttributes; //導入依賴的package包/類
@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);
}
 
開發者ID:yu199195,項目名稱:myth,代碼行數:18,代碼來源:SpringCloudMythTransactionInterceptor.java

示例12: doFilterInternal

import org.springframework.web.context.request.ServletRequestAttributes; //導入依賴的package包/類
@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();
	}
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:20,代碼來源:RequestContextFilter.java

示例13: accessDataReadOnly

import org.springframework.web.context.request.ServletRequestAttributes; //導入依賴的package包/類
@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();
}
 
開發者ID:oneops,項目名稱:oneops,代碼行數:24,代碼來源:DataAccessAspect.java

示例14: execution

import org.springframework.web.context.request.ServletRequestAttributes; //導入依賴的package包/類
@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;
}
 
開發者ID:nielsutrecht,項目名稱:spring-boot-aop,代碼行數:24,代碼來源:RequestLogAspect.java

示例15: before

import org.springframework.web.context.request.ServletRequestAttributes; //導入依賴的package包/類
@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);
}
 
開發者ID:fier-liu,項目名稱:FCat,代碼行數:23,代碼來源:LogAspect.java


注:本文中的org.springframework.web.context.request.ServletRequestAttributes類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。