org.springframework.web.context.request.ServletRequestAttributes Java Examples

The following examples show how to use org.springframework.web.context.request.ServletRequestAttributes. 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: RequestContextFilter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected void doFilterInternal(
		HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
		throws ServletException, IOException {

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

	try {
		filterChain.doFilter(request, response);
	}
	finally {
		resetContextHolders();
		if (logger.isDebugEnabled()) {
			logger.debug("Cleared thread-bound request context: " + request);
		}
		attributes.requestCompleted();
	}
}
 
Example #2
Source File: AdditionalCertificateValidationsAspectShould.java    From mutual-tls-ssl with Apache License 2.0 6 votes vote down vote up
@Test
public void validateCertificateForUnrecognizedCommonNameReturnsBadRequestHttpStatus() throws Throwable {
    var proceedingJoinPoint = mock(ProceedingJoinPoint.class);
    var additionalCertificateValidations = createAdditionalCertificateValidations();

    X509Certificate x509Certificate = mock(X509Certificate.class);
    X509Certificate[] x509Certificates = new X509Certificate[]{x509Certificate};
    X500Principal x500Principal = mock(X500Principal.class);

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setAttribute("javax.servlet.request.X509Certificate", x509Certificates);
    RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));

    when(x509Certificate.getSubjectX500Principal()).thenReturn(x500Principal);
    when(x500Principal.getName()).thenReturn("qwertyuiop");

    Object response = victim.validate(proceedingJoinPoint, additionalCertificateValidations);

    verify(proceedingJoinPoint, times(0)).proceed();
    assertThat(response).isInstanceOf(ResponseEntity.class);

    ResponseEntity responseEntity = (ResponseEntity) response;
    assertThat(responseEntity.getStatusCode().value()).isEqualTo(400);
    assertThat(responseEntity.getBody()).isEqualTo("This certificate is not a valid one");
}
 
Example #3
Source File: OrderChargeController.java    From seckill-rocketmq with Apache License 2.0 6 votes vote down vote up
/**
 * 平台下单接口
 * @param chargeOrderRequest
 * @return
 */
@RequestMapping(value = "charge.do", method = {RequestMethod.POST})
public @ResponseBody Result chargeOrder(@ModelAttribute ChargeOrderRequest chargeOrderRequest) {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    String sessionId = attributes.getSessionId();
    // 下单前置参数校验
    if (!secKillChargeService.checkParamsBeforeSecKillCharge(chargeOrderRequest, sessionId)) {
        return Result.error(CodeMsg.PARAM_INVALID);
    }
    // 前置商品校验
    String prodId = chargeOrderRequest.getProdId();
    if (!secKillChargeService.checkProdConfigBeforeKillCharge(prodId, sessionId)) {
        return Result.error(CodeMsg.PRODUCT_NOT_EXIST);
    }
    // 前置预减库存
    if (!secKillProductConfig.preReduceProdStock(prodId)) {
        return Result.error(CodeMsg.PRODUCT_STOCK_NOT_ENOUGH);
    }
    // 秒杀订单入队
    return secKillChargeService.secKillOrderEnqueue(chargeOrderRequest, sessionId);
}
 
Example #4
Source File: AutomaticDispatcherUrlServiceTest.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void testLocalizeConfigured() {
	AutomaticDispatcherUrlService adus = new AutomaticDispatcherUrlService();
	adus.setLocalDispatcherUrl("http://my:8080/local/dispatcher/");

	// set mock request in context holder
	MockHttpServletRequest mockRequest = new MockHttpServletRequest();
	mockRequest.setScheme("http");
	mockRequest.setServerName("myhost");
	mockRequest.setServerPort(80);
	mockRequest.setLocalName("localhost");
	mockRequest.setLocalPort(8080);
	mockRequest.setContextPath("/test");
	mockRequest.addHeader(X_FORWARD_HOST_HEADER, "geomajas.org");
	ServletRequestAttributes attributes = new ServletRequestAttributes(mockRequest);
	RequestContextHolder.setRequestAttributes(attributes);
	Assert.assertEquals("http://my:8080/local/dispatcher/something", adus.localize("http://geomajas.org/test/d/something"));

	// clean up
	RequestContextHolder.setRequestAttributes(null);
}
 
Example #5
Source File: BaseApiController.java    From pybbs with GNU Affero General Public License v3.0 6 votes vote down vote up
protected User getApiUser(boolean required) {
    HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder
            .getRequestAttributes())).getRequest();
    String token = request.getHeader("token");
    //    String token = request.getParameter("token");
    if (required) { // token必须要
        // 判断token是否存在,不存在要抛异常
        ApiAssert.notEmpty(token, "token不能为空");
        // 用token查用户信息,查不到要抛异常
        User user = userService.selectByToken(token);
        ApiAssert.notNull(user, "token不正确,请在网站上登录自己的帐号,然后进入个人设置页面扫描二维码获取token");
        return user;
    } else { // token非必须
        // 先判断token存在不,不存在直接返回null
        if (StringUtils.isEmpty(token)) return null;
        // 如果token存在,直接查询用户信息,不管查到查不到,都直接返回
        return userService.selectByToken(token);
    }
}
 
Example #6
Source File: MsgService.java    From jshERP with GNU General Public License v3.0 6 votes vote down vote up
/**
 * create by: qiankunpingtai
 * website:https://qiankunpingtai.cn
 * description:
 *  逻辑删除角色信息
 * create time: 2019/3/28 15:44
 * @Param: ids
 * @return int
 */
@Transactional(value = "transactionManager", rollbackFor = Exception.class)
public int batchDeleteMsgByIds(String ids) throws Exception{
    logService.insertLog("序列号",
            new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_DELETE).append(ids).toString(),
            ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
    String [] idArray=ids.split(",");
    int result=0;
    try{
        result=msgMapperEx.batchDeleteMsgByIds(idArray);
    }catch(Exception e){
        logger.error("异常码[{}],异常提示[{}],异常[{}]",
                ExceptionConstants.DATA_WRITE_FAIL_CODE, ExceptionConstants.DATA_WRITE_FAIL_MSG,e);
        throw new BusinessRunTimeException(ExceptionConstants.DATA_WRITE_FAIL_CODE,
                ExceptionConstants.DATA_WRITE_FAIL_MSG);
    }
    return result;
}
 
Example #7
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 #8
Source File: WebExceptionAspect.java    From softservice with MIT License 6 votes vote down vote up
/**
 * 将内容输出到浏览器
 *
 * @param content
 *            输出内容
 */
private void writeContent(String content) {
    HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
            .getResponse();
    response.reset();
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Content-Type", "text/plain;charset=UTF-8");
    response.setHeader("icop-content-type", "exception");
    PrintWriter writer = null;
    try {
        writer = response.getWriter();

        writer.print((content == null) ? "" : content);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #9
Source File: CustomAuthenticationProvider.java    From spring-security with Apache License 2.0 6 votes vote down vote up
/**
 * 验证用户输入的验证码
 * @param inputVerifyCode
 * @return
 */
public boolean validateVerifyCode(String inputVerifyCode){
    //获取当前线程绑定的request对象
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    // 这个VerifyCodeFactory.SESSION_KEY是在servlet中存入session的名字
    HttpSession session = request.getSession();
    String verifyCode = (String)session.getAttribute(VerifyCodeUtil.SESSION_KEY);
    if(null == verifyCode || verifyCode.isEmpty()){
        log.warn("验证码过期请重新验证");
        throw new DisabledException("验证码过期,请重新验证");
    }
    // 不分区大小写
    verifyCode = verifyCode.toLowerCase();
    inputVerifyCode = inputVerifyCode.toLowerCase();

    log.info("验证码:{}, 用户输入:{}", verifyCode, inputVerifyCode);

    return verifyCode.equals(inputVerifyCode);
}
 
Example #10
Source File: GrayServerFilter.java    From summerframework with Apache License 2.0 6 votes vote down vote up
@Override
public List<Server> match(List<Server> servers) {
    if (servers == null || servers.size() == 0) {
        return servers;
    }
    ServletRequestAttributes requestAttributes =
        (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
    if (requestAttributes == null) {
        logger.debug("No servletRequestAttributes in current thread. Match all servers");
        return Lists.newArrayList(servers);
    }
    HttpServletRequest request = requestAttributes.getRequest();

    List<Map<String, String>> matchList = grayScriptEngine.execute(servers, convertRequest(request));
    List<Server> allServers = new ArrayList<>();
    allServers.addAll(servers);
    for (Map<String, String> m : matchList) {
        allServers = match(allServers, m);
    }
    if (allServers.size() == 0) {
        logger.info("No server found");
    }
    return allServers;
}
 
Example #11
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 #12
Source File: ControllerLogAop.java    From halo with GNU General Public License v3.0 6 votes vote down vote up
@Around("controller()")
public Object controller(ProceedingJoinPoint joinPoint) throws Throwable {
    String className = joinPoint.getTarget().getClass().getSimpleName();
    String methodName = joinPoint.getSignature().getName();
    Object[] args = joinPoint.getArgs();

    // Get request attribute
    ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = Objects.requireNonNull(requestAttributes).getRequest();

    printRequestLog(request, className, methodName, args);
    long start = System.currentTimeMillis();
    Object returnObj = joinPoint.proceed();
    printResponseLog(request, className, methodName, returnObj, System.currentTimeMillis() - start);
    return returnObj;
}
 
Example #13
Source File: WebLogAspect.java    From my-site with Apache License 2.0 6 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();
    HttpSession session = request.getSession();
    // 记录下请求内容
    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 #14
Source File: SupplierService.java    From jshERP with GNU General Public License v3.0 6 votes vote down vote up
@Transactional(value = "transactionManager", rollbackFor = Exception.class)
public BaseResponseInfo importExcel(List<Supplier> mList) throws Exception {
    logService.insertLog("商家",
            new StringBuffer(BusinessConstants.LOG_OPERATION_TYPE_IMPORT).append(mList.size()).append(BusinessConstants.LOG_DATA_UNIT).toString(),
            ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest());
    BaseResponseInfo info = new BaseResponseInfo();
    Map<String, Object> data = new HashMap<String, Object>();
    try {
        for(Supplier s: mList) {
            supplierMapper.insertSelective(s);
        }
        info.code = 200;
        data.put("message", "成功");
    } catch (Exception e) {
        e.printStackTrace();
        info.code = 500;
        data.put("message", e.getMessage());
    }
    info.data = data;
    return info;
}
 
Example #15
Source File: AuthContext.java    From staffjoy with MIT License 5 votes vote down vote up
private static String getRequetHeader(String headerName) {
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes instanceof ServletRequestAttributes) {
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
        String value = request.getHeader(headerName);
        return value;
    }
    return null;
}
 
Example #16
Source File: AopLog.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 后置操作
 */
@AfterReturning("log()")
public void afterReturning() {
	ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
	HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();

	Long start = (Long) request.getAttribute(START_TIME);
	Long end = System.currentTimeMillis();
	log.info("【请求耗时】:{}毫秒", end - start);

	String header = request.getHeader("User-Agent");
	UserAgent userAgent = UserAgent.parseUserAgentString(header);
	log.info("【浏览器类型】:{},【操作系统】:{},【原始User-Agent】:{}", userAgent.getBrowser().toString(), userAgent.getOperatingSystem().toString(), header);
}
 
Example #17
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 #18
Source File: ShiroConfigService.java    From layui-admin with MIT License 5 votes vote down vote up
/**
 * 更新权限,解决需要重启tomcat才能生效权限的问题
 */
public void updatePermission() {
    try {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        ServletContext servletContext = request.getSession().getServletContext();
        AbstractShiroFilter shiroFilter = (AbstractShiroFilter) WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext).getBean("myShiroFilter");

        synchronized (shiroFilter) {
            // 获取过滤管理器
            PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();
            DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();
            // 清空初始权限配置
            manager.getFilterChains().clear();
            // 重新获取资源
            Map<String, String> chains = loadFilterChainDefinitions();

            for (Map.Entry<String, String> entry : chains.entrySet()) {
                String url = entry.getKey();
                String chainDefinition = entry.getValue().trim().replace(" ", "");

                manager.createChain(url, chainDefinition);
            }
            log.info("更新权限成功!!");
        }
    } catch (Exception e) {
        log.error("更新权限到shiro异常", e);
    }
}
 
Example #19
Source File: GeeTestAspect.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
private void sendVerifyCode(JoinPoint joinPoint) {
    startTime.set(System.currentTimeMillis());
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    String ip = request.getHeader("X-Real-IP");
    // 记录下请求内容
    log.info("请求路径 : " + request.getRequestURL().toString());
    log.info("请求方式 : " + request.getMethod());
    log.info("请求IP  : " + ip);
    log.info("请求方法 : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
    log.info("请求参数 : " + Arrays.toString(joinPoint.getArgs()));
}
 
Example #20
Source File: MvcUriComponentsBuilder.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Nullable
private static WebApplicationContext getWebApplicationContext() {
	RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
	if (requestAttributes == null) {
		return null;
	}
	HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
	String attributeName = DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE;
	WebApplicationContext wac = (WebApplicationContext) request.getAttribute(attributeName);
	if (wac == null) {
		return null;
	}
	return wac;
}
 
Example #21
Source File: LogClientTypeAspectShould.java    From mutual-tls-ssl with Apache License 2.0 5 votes vote down vote up
@Test
public void notLogClientTypeIfAbsent() {
    LogCaptor<LogClientTypeAspect> logCaptor = LogCaptor.forClass(LogClientTypeAspect.class);

    MockHttpServletRequest request = new MockHttpServletRequest();
    RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));

    logClientTypeAspect.logClientTypeIfPresent();

    List<String> logs = logCaptor.getLogs();
    assertThat(logs).isEmpty();
}
 
Example #22
Source File: ControllerLogAspect.java    From short-url with Apache License 2.0 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 #23
Source File: ValidateCodeFilter.java    From blog-sample with Apache License 2.0 5 votes vote down vote up
private boolean validateVerify(String inputVerify) {
    //获取当前线程绑定的request对象
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    // 不分区大小写
    // 这个validateCode是在servlet中存入session的名字
    String validateCode = ((String) request.getSession().getAttribute("validateCode")).toLowerCase();
    inputVerify = inputVerify.toLowerCase();

    log.info("验证码:{}, 用户输入:{}", validateCode, inputVerify);
    return validateCode.equals(inputVerify);
}
 
Example #24
Source File: CatnapMessageConverter.java    From catnap with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean supports(Class<?> clazz) {
    HttpServletRequest httpRequest = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();

    if (httpRequest.getParameter("fields") != null) {
        return Object.class.isAssignableFrom(clazz);
    }

    return false;
}
 
Example #25
Source File: TokenRequiredAspect.java    From Building-RESTful-Web-Services-with-Spring-5-Second-Edition with MIT License 5 votes vote down vote up
@Before("@annotation(tokenRequired)")
public void tokenRequiredWithAnnotation(TokenRequired tokenRequired) throws Throwable{
	
	System.out.println("Before tokenRequiredWithAnnotation");
	
	ServletRequestAttributes reqAttributes = (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();
	HttpServletRequest request = reqAttributes.getRequest();
	
	// checks for token in request header
	String tokenInHeader = request.getHeader("token");
	
	if(StringUtils.isEmpty(tokenInHeader)){
		throw new IllegalArgumentException("Empty token");
	}
	
	Claims claims = Jwts.parser()         
		       .setSigningKey(DatatypeConverter.parseBase64Binary(SecurityServiceImpl.secretKey))
		       .parseClaimsJws(tokenInHeader).getBody();
	
	if(claims == null || claims.getSubject() == null){
		throw new IllegalArgumentException("Token Error : Claim is null");
	}
	
	if(!claims.getSubject().equalsIgnoreCase("packt")){
		throw new IllegalArgumentException("Subject doesn't match in the token");
	}
}
 
Example #26
Source File: SysLogAspect.java    From pre with GNU General Public License v3.0 5 votes vote down vote up
/***
 * 拦截控制层的操作日志
 * @param joinPoint
 * @return
 * @throws Throwable
 */
@Before(value = "sysLogAspect()")
public void recordLog(JoinPoint joinPoint) throws Throwable {
    SysLog sysLog = new SysLog();
    //将当前实体保存到threadLocal
    sysLogThreadLocal.set(sysLog);
    // 开始时间
    long beginTime = Instant.now().toEpochMilli();
    HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    PreSecurityUser securityUser = SecurityUtil.getUser();
    sysLog.setUserName(securityUser.getUsername());
    sysLog.setActionUrl(URLUtil.getPath(request.getRequestURI()));
    sysLog.setStartTime(LocalDateTime.now());
    String ip = ServletUtil.getClientIP(request);
    sysLog.setIp(ip);
    sysLog.setLocation(IPUtil.getCityInfo(ip));
    sysLog.setRequestMethod(request.getMethod());
    String uaStr = request.getHeader("user-agent");
    sysLog.setBrowser(UserAgentUtil.parse(uaStr).getBrowser().toString());
    sysLog.setOs(UserAgentUtil.parse(uaStr).getOs().toString());

    //访问目标方法的参数 可动态改变参数值
    Object[] args = joinPoint.getArgs();
    //获取执行的方法名
    sysLog.setActionMethod(joinPoint.getSignature().getName());
    // 类名
    sysLog.setClassPath(joinPoint.getTarget().getClass().getName());
    sysLog.setActionMethod(joinPoint.getSignature().getName());
    sysLog.setFinishTime(LocalDateTime.now());
    // 参数
    sysLog.setParams(Arrays.toString(args));
    sysLog.setDescription(LogUtil.getControllerMethodDescription(joinPoint));
    long endTime = Instant.now().toEpochMilli();
    sysLog.setConsumingTime(endTime - beginTime);
}
 
Example #27
Source File: FoxbpmUserInterceptor.java    From FoxBPM with Apache License 2.0 5 votes vote down vote up
public void before(Method method, Object[] params, Object implObj) throws Throwable {
	HttpSession session = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession(); 
	if(session == null || session.getAttribute("userId") == null){
		throw new RuntimeException("未登陆用户不能进行此操作!");
	}
	String userId = (String)session.getAttribute("userId");
	Authentication.setAuthenticatedUserId(userId);
}
 
Example #28
Source File: MetadataApiControllerTest.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
@BeforeEach
void setUpBeforeEach() {
  metadataApiController =
      new MetadataApiController(
          metadataApiService,
          entityTypeResponseMapper,
          entityTypeRequestMapper,
          attributeResponseMapper,
          attributeRequestMapper);
  RequestContextHolder.setRequestAttributes(
      new ServletRequestAttributes(new MockHttpServletRequest()));
  MessageSourceHolder.setMessageSource(messageSource);
}
 
Example #29
Source File: SessionUtils.java    From flash-waimai with MIT License 5 votes vote down vote up
public static HttpSession getSession() {
	if (RequestContextHolder.getRequestAttributes() == null) {
		return null;
	}
	HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	return request.getSession();
}
 
Example #30
Source File: CustomAuthenticationProvider.java    From blog-sample with Apache License 2.0 5 votes vote down vote up
private boolean validateVerify(String inputVerify) {
    //获取当前线程绑定的request对象
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    // 不分区大小写
    // 这个validateCode是在servlet中存入session的名字
    String validateCode = ((String) request.getSession().getAttribute("validateCode")).toLowerCase();
    inputVerify = inputVerify.toLowerCase();

    System.out.println("验证码:" + validateCode + "用户输入:" + inputVerify);

    return validateCode.equals(inputVerify);
}