Java Code Examples for org.springframework.web.context.request.ServletRequestAttributes#getRequest()

The following examples show how to use org.springframework.web.context.request.ServletRequestAttributes#getRequest() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PubServiceImpl.java    From SuperBoot with MIT License 6 votes vote down vote up
/**
 * 获取ASE密钥信息
 *
 * @return
 */
private String getAesKey() {
    ServletRequestAttributes attributes = getServletRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    String secretKey = request.getHeader(BaseConstants.SECRET_KEY);
    if (StrUtil.isNotBlank(secretKey)) {
        //执行RSA解密
        try {
            return rsaDecrypt(secretKey);
        } catch (Exception e) {
            throw new BaseException(StatusCode.DECODE_FAIL);
        }
    }

    return null;
}
 
Example 2
Source File: HttpAspect.java    From SpringBoot-Course with MIT License 6 votes vote down vote up
@Before("log()")
public void doBefore(JoinPoint joinPoint) {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();

    Map params = new HashMap();
    params.put("url", request.getRequestURL()); // 获取请求的url
    params.put("method", request.getMethod()); // 获取请求的方式
    params.put("ip", request.getRemoteAddr()); // 获取请求的ip地址
    params.put("className", joinPoint.getSignature().getDeclaringTypeName()); // 获取类名
    params.put("classMethod", joinPoint.getSignature().getName()); // 获取类方法
    params.put("args", joinPoint.getArgs()); // 请求参数

    // 输出格式化后的json字符串
    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    logger.info("REQUEST: {}", gson.toJson(params));
}
 
Example 3
Source File: LogHandle.java    From SpringBoot-Dubbo-Docker-Jenkins with Apache License 2.0 6 votes vote down vote up
@Around("restLog()")
public void doAround(ProceedingJoinPoint joinPoint) throws Throwable {

    // 生成本次请求时间戳
    String timestamp = System.currentTimeMillis()+"";

    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(timestamp + ", url: {}, method: {}, uri: {}, params: {}", url, method, uri, queryString);

    // result的值就是被拦截方法的返回值
    Object result = joinPoint.proceed();
    logger.info(timestamp + " , " + result.toString());
}
 
Example 4
Source File: WebLogAspect.java    From yyblog with MIT License 6 votes vote down vote up
@Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求,记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 记录下请求内容
        logger.info("请求地址 : " + request.getRequestURL().toString());
        logger.info("HTTP METHOD : " + request.getMethod());
        // 获取真实的ip地址
        //logger.info("IP : " + WebUtils.getIpAddress(request));
        logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "."
                + joinPoint.getSignature().getName());
        logger.info("参数 : " + Arrays.toString(joinPoint.getArgs()));
//        loggger.info("参数 : " + joinPoint.getArgs());

    }
 
Example 5
Source File: WebLogAspect.java    From ProxyPool with Apache License 2.0 6 votes vote down vote up
@Before("log()")
public void doBeforeController(JoinPoint joinPoint) {

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

    // 记录下请求内容
    log.debug("URL : " + request.getRequestURL().toString());
    log.debug("HTTP_METHOD : " + request.getMethod());
    log.debug("IP : " + request.getRemoteAddr());
    log.debug("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
    log.debug("ARGS : " + Arrays.toString(joinPoint.getArgs()));
    //获取所有参数方法一:
    Enumeration<String> enu = request.getParameterNames();
    while (enu.hasMoreElements()) {
        String paraName = (String) enu.nextElement();
        System.out.println(paraName + ": " + request.getParameter(paraName));
    }
}
 
Example 6
Source File: UmsAdminServiceImpl.java    From macrozheng-mall with MIT License 5 votes vote down vote up
/**
 * 添加登录记录
 * @param username 用户名
 */
private void insertLoginLog(String username) {
    UmsAdmin admin = getAdminByUsername(username);
    UmsAdminLoginLog loginLog = new UmsAdminLoginLog();
    loginLog.setAdminId(admin.getId());
    loginLog.setCreateTime(new Date());
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    loginLog.setIp(request.getRemoteAddr());
    loginLogMapper.insert(loginLog);
}
 
Example 7
Source File: WebLogAspect.java    From mall-learning with Apache License 2.0 5 votes vote down vote up
@Around("webLog()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
    long startTime = System.currentTimeMillis();
    //获取当前请求对象
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    //记录请求信息
    WebLog webLog = new WebLog();
    Object result = joinPoint.proceed();
    Signature signature = joinPoint.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();
    if (method.isAnnotationPresent(ApiOperation.class)) {
        ApiOperation apiOperation = method.getAnnotation(ApiOperation.class);
        webLog.setDescription(apiOperation.value());
    }
    long endTime = System.currentTimeMillis();
    String urlStr = request.getRequestURL().toString();
    webLog.setBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
    webLog.setIp(request.getRemoteUser());
    webLog.setMethod(request.getMethod());
    webLog.setParameter(getParameter(method, joinPoint.getArgs()));
    webLog.setResult(result);
    webLog.setSpendTime((int) (endTime - startTime));
    webLog.setStartTime(startTime);
    webLog.setUri(request.getRequestURI());
    webLog.setUrl(request.getRequestURL().toString());
    LOGGER.info("{}", JSONUtil.parse(webLog));
    return result;
}
 
Example 8
Source File: BaseController.java    From feiqu-opensource with Apache License 2.0 5 votes vote down vote up
protected FqUserCache getCurrentUser(){
    ServletRequestAttributes servletRequestAttributes = ((ServletRequestAttributes) RequestContextHolder
            .getRequestAttributes());
    HttpServletRequest request = servletRequestAttributes
            .getRequest();
    HttpServletResponse response = servletRequestAttributes
            .getResponse();
    WebUtil webUtil = SpringUtils.getBean(WebUtil.class);
    return webUtil.currentUser(request,response);
}
 
Example 9
Source File: WebLogAspect.java    From HIS with Apache License 2.0 5 votes vote down vote up
@Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //记录请求信息(通过logstash传入elasticsearch)
        WebLog webLog = new WebLog();
        Object result = joinPoint.proceed();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method.isAnnotationPresent(ApiOperation.class)) {
            ApiOperation log = method.getAnnotation(ApiOperation.class);
            webLog.setDescription(log.value());
        }
        long endTime = System.currentTimeMillis();
        String urlStr = request.getRequestURL().toString();
        webLog.setBasePath(StrUtil.removeSuffix(urlStr, URLUtil.url(urlStr).getPath()));
        webLog.setIp(request.getRemoteUser());
        webLog.setMethod(request.getMethod());
        webLog.setParameter(getParameter(method, joinPoint.getArgs()));
        webLog.setResult(result);
        webLog.setSpendTime((int) (endTime - startTime.get()));
        webLog.setStartTime(startTime.get());
        webLog.setUri(request.getRequestURI());
        webLog.setUrl(request.getRequestURL().toString());
        Map<String,Object> logMap = new HashMap<>();
        logMap.put("url",webLog.getUrl());
        logMap.put("method",webLog.getMethod());
        logMap.put("parameter",webLog.getParameter());
        logMap.put("spendTime",webLog.getSpendTime());
        logMap.put("description",webLog.getDescription());
//        LOGGER.info("{}", JSONUtil.parse(webLog));
        LOGGER.info(Markers.appendEntries(logMap), JSONUtil.parse(webLog).toString());
        return result;
    }
 
Example 10
Source File: CustomFeignConfig.java    From spring-microservice-exam with MIT License 5 votes vote down vote up
private HttpServletRequest getHttpServletRequest() {
    try {
        // hystrix隔离策略会导致RequestContextHolder.getRequestAttributes()返回null
        // 解决方案:http://www.itmuch.com/spring-cloud-sum/hystrix-threadlocal/
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null)
            return attributes.getRequest();
        return null;
    } catch (Exception e) {
        return null;
    }
}
 
Example 11
Source File: UserSupplier.java    From Gatekeeper with Apache License 2.0 5 votes vote down vote up
/**
 * Supplies a UserProfile instance representing the currently active user.
 *
 * Currently checks if an active HttpServletRequest is available and if so looks up the
 * UserPrincipal contained there.  If the active request does not contain a UserProfile
 * then an IllegalStateException is thrown.
 *
 * If there's no ServletRequestAttribute than throw an IllegalStateException
 *
 * @return the currently active UserProfile
 */
@Override
public IGatekeeperUserProfile get() {
    ServletRequestAttributes requestAttributes =
            (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    if (requestAttributes != null) {
        HttpServletRequest request = requestAttributes.getRequest();
        if (request.getUserPrincipal() == null) {
            throw new IllegalStateException("Could not determine user on request");
        }
        return (IGatekeeperUserProfile) request.getUserPrincipal();
    }

    throw new IllegalStateException("Could not determine user on request");
}
 
Example 12
Source File: WebLogAspect.java    From docs-manage with MIT 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 13
Source File: CookieUtils.java    From mogu_blog_v2 with Apache License 2.0 5 votes vote down vote up
/**
 * 设置Cookie的值,并使其在指定时间内生效
 *
 * @param cookieMaxage cookie生效的最大秒数
 */
private static final void doSetCookie(String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
    ServletRequestAttributes attribute = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attribute.getRequest();
    HttpServletResponse response = attribute.getResponse();
    try {
        if (cookieValue == null) {
            cookieValue = "";
        } else if (isEncode) {
            cookieValue = URLEncoder.encode(cookieValue, "utf-8");
        }
        Cookie cookie = new Cookie(cookieName, cookieValue);
        if (cookieMaxage > 0) {
            cookie.setMaxAge(cookieMaxage);
        }
        if (null != request) {// 设置域名的cookie
            String domainName = getDomainName(request);
            System.out.println(domainName);
            if (!"localhost".equals(domainName)) {
                cookie.setDomain(domainName);
            }
        }
        cookie.setPath("/");
        response.addCookie(cookie);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 14
Source File: UpdatePayAspect.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
public void check(JoinPoint joinPoint) throws Exception {
    startTime.set(System.currentTimeMillis());
    // 接收到请求,记录请求内容
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    AuthMember authMember = (AuthMember) request.getSession().getAttribute(SESSION_MEMBER);
    List<Order> list1 = orderService.getAllOrdering(authMember.getId());
    if (list1.size()>0){
        throw new IllegalArgumentException(msService.getMessage("HAVE_ORDER_ING"));
    }
    List<Advertise> list = advertiseService.getAllPutOnAdvertis(authMember.getId());
    if (list.size()>0){
        throw new IllegalArgumentException(msService.getMessage("MUST_PUT_OFF_ALL_ADVERTISE"));
    }
}
 
Example 15
Source File: DaoAspect.java    From Qualitis with Apache License 2.0 5 votes vote down vote up
@AfterReturning(pointcut = "ruleTemplateAspect()", returning = "object")
public void ruleTemplateAspectAfter(JoinPoint joinPoint, Object object) throws InvocationTargetException, IllegalAccessException {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    String localeStr = request.getHeader("Content-Language");
    if (object != null) {
        replaceMessage(object, localeStr);
    }
}
 
Example 16
Source File: LogAspect.java    From Jantent with MIT 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 17
Source File: LoggingAop.java    From ChengFeng1.5 with MIT License 4 votes vote down vote up
@AfterReturning(returning = "ret",pointcut = "chengfengLog()")
public void doAfterReturn(Object ret){
    ServletRequestAttributes attributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    log.debug(request.getRequestURL().append(" 耗时: ").append(System.currentTimeMillis()-startTime.get()).toString());
}
 
Example 18
Source File: WebRequestLogAspect.java    From oauth2-server with MIT License 4 votes vote down vote up
/**
 * 接收到请求,记录请求内容
 *
 * @param joinPoint
 * @throws Throwable
 */
@Before("wsLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
    if (log.isInfoEnabled()) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            Map<String, String[]> parameters = request.getParameterMap();
            try {
                String parametersString = null;
                String requestBody = null;
                if (parameters != null) {
                    parametersString = JsonUtil.multiValueMapToJsonString(parameters);
                }
                MethodSignature signature = (MethodSignature) joinPoint.getSignature();
                //获取被拦截的方法
                Method method = signature.getMethod();
                Object object = getAnnotatedParameterValueRequestBody(method, joinPoint.getArgs());
                if (object != null) {
                    requestBody = JsonUtil.objectToJsonString(object);
                }
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append("\nRequest from = ");
                stringBuffer.append(ClientIpUtil.getIpAddress(request));
                stringBuffer.append(";\n");
                stringBuffer.append("uri = ");
                stringBuffer.append(request.getRequestURL().toString());
                stringBuffer.append(";\n");
                stringBuffer.append("request method = ");
                stringBuffer.append(request.getMethod());
                stringBuffer.append(";\n");
                stringBuffer.append("content type = ");
                stringBuffer.append(request.getContentType());
                stringBuffer.append(";\n");
                stringBuffer.append("request parameters = ");
                stringBuffer.append(parametersString);
                stringBuffer.append(";\n");
                stringBuffer.append("request body = ");
                stringBuffer.append(requestBody);
                stringBuffer.append(";\n");

                log.info(stringBuffer.toString());
                String headers = JsonUtil.objectToJsonString(getHeadersInfo(request));
                log.info("headers:" + headers);
            } catch (Exception e) {
                log.info("log http request Exception: ", e);
            }
        }
    }
}
 
Example 19
Source File: WebApplicationContextUtils.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public WebRequest getObject() {
	ServletRequestAttributes requestAttr = currentRequestAttributes();
	return new ServletWebRequest(requestAttr.getRequest(), requestAttr.getResponse());
}
 
Example 20
Source File: FeignRequestInterceptorConfig.java    From sophia_scaffolding with Apache License 2.0 4 votes vote down vote up
/**
 * Create a template with the header of provided name and extracted extract
 * 1. 如果使用 非web 请求,header 区别
 * 2. 根据authentication 还原请求token
 * 3.查看是否有内部调用标志
 *
 * @param template
 */
@Override
public void apply(RequestTemplate template) {
    Collection<String> fromHeader = template.headers().get(FROM);
    if (CollUtil.isNotEmpty(fromHeader) && fromHeader.contains(FROM_IN)) {
        log.info("内部调用feign");
        String s = "?client_id=" + clientId + "&client_secret=" + clientSecret + "&grant_type=client_credentials&scope=all";
        String sr = HttpCallOtherInterfaceUtil.callOtherInterface(url, "/api/auth/oauth/token" + s);
        Map srmap = JSON.parseObject(sr);
        if (null == srmap) {
            log.info("内部调用feign传递失败");
            return;
        }
        String access_token = (String) srmap.get("access_token");
        if (StringUtils.isBlank(access_token)){
            access_token = (String) srmap.get("value");
        }
        log.info(access_token);
        template.header(AUTHORIZATION_HEADER, "Bearer " + access_token);
        return;
    }
    log.info("外部调用feign");
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    if (request != null) {
        log.info("调用feign传递header携带token");
        //只携带token
        // String authorization = request.getHeader(AUTHORIZATION_HEADER);
        //requestTemplate.header("Authorization", authorization);
        // log.info("Authorization :\t\t" + authorization);
        //携带全部
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                template.header(name, values);
                log.info("name :\t\t" + name);
                log.info("values : \t\t" + values);
            }
        }
    }
}