Java Code Examples for org.springframework.web.bind.annotation.RequestMapping#value()

The following examples show how to use org.springframework.web.bind.annotation.RequestMapping#value() . 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: CrossOriginTests.java    From spring-analysis-note with MIT License 7 votes vote down vote up
@Override
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
	RequestMapping annotation = AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class);
	if (annotation != null) {
		return new RequestMappingInfo(
				new PatternsRequestCondition(annotation.value(), getUrlPathHelper(), getPathMatcher(), true, true),
				new RequestMethodsRequestCondition(annotation.method()),
				new ParamsRequestCondition(annotation.params()),
				new HeadersRequestCondition(annotation.headers()),
				new ConsumesRequestCondition(annotation.consumes(), annotation.headers()),
				new ProducesRequestCondition(annotation.produces(), annotation.headers()), null);
	}
	else {
		return null;
	}
}
 
Example 2
Source File: AnnotationMethodHandlerAdapter.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected boolean isHandlerMethod(Method method) {
	if (this.mappings.containsKey(method)) {
		return true;
	}
	RequestMapping mapping = AnnotationUtils.findAnnotation(method, RequestMapping.class);
	if (mapping != null) {
		String[] patterns = mapping.value();
		RequestMethod[] methods = new RequestMethod[0];
		String[] params = new String[0];
		String[] headers = new String[0];
		if (!hasTypeLevelMapping() || !Arrays.equals(mapping.method(), getTypeLevelMapping().method())) {
			methods = mapping.method();
		}
		if (!hasTypeLevelMapping() || !Arrays.equals(mapping.params(), getTypeLevelMapping().params())) {
			params = mapping.params();
		}
		if (!hasTypeLevelMapping() || !Arrays.equals(mapping.headers(), getTypeLevelMapping().headers())) {
			headers = mapping.headers();
		}
		RequestMappingInfo mappingInfo = new RequestMappingInfo(patterns, methods, params, headers);
		this.mappings.put(method, mappingInfo);
		return true;
	}
	return false;
}
 
Example 3
Source File: RequestMappingInfoHandlerMappingTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
	RequestMapping annotation = AnnotationUtils.findAnnotation(method, RequestMapping.class);
	if (annotation != null) {
		return new RequestMappingInfo(
			new PatternsRequestCondition(annotation.value(), getUrlPathHelper(), getPathMatcher(), true, true),
			new RequestMethodsRequestCondition(annotation.method()),
			new ParamsRequestCondition(annotation.params()),
			new HeadersRequestCondition(annotation.headers()),
			new ConsumesRequestCondition(annotation.consumes(), annotation.headers()),
			new ProducesRequestCondition(annotation.produces(), annotation.headers()), null);
	}
	else {
		return null;
	}
}
 
Example 4
Source File: RequestMappingInfoHandlerMappingTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
	RequestMapping annot = AnnotationUtils.findAnnotation(method, RequestMapping.class);
	if (annot != null) {
		return new RequestMappingInfo(
			new PatternsRequestCondition(annot.value(), getUrlPathHelper(), getPathMatcher(), true, true),
			new RequestMethodsRequestCondition(annot.method()),
			new ParamsRequestCondition(annot.params()),
			new HeadersRequestCondition(annot.headers()),
			new ConsumesRequestCondition(annot.consumes(), annot.headers()),
			new ProducesRequestCondition(annot.produces(), annot.headers()), null);
	}
	else {
		return null;
	}
}
 
Example 5
Source File: CrossOriginTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
	RequestMapping annotation = AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class);
	if (annotation != null) {
		return new RequestMappingInfo(
				new PatternsRequestCondition(annotation.value(), getUrlPathHelper(), getPathMatcher(), true, true),
				new RequestMethodsRequestCondition(annotation.method()),
				new ParamsRequestCondition(annotation.params()),
				new HeadersRequestCondition(annotation.headers()),
				new ConsumesRequestCondition(annotation.consumes(), annotation.headers()),
				new ProducesRequestCondition(annotation.produces(), annotation.headers()), null);
	}
	else {
		return null;
	}
}
 
Example 6
Source File: SpringUtils.java    From swagger-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
    * Extracts all routes from the annotated class
    *
    * @param controllerClazz
    *            Instrospected class
    * @return At least 1 route value (empty string)
    */
   public static String[] getControllerResquestMapping(Class<?> controllerClazz) {
String[] controllerRequestMappingValues = {};

// Determine if we will use class-level requestmapping or dummy string
RequestMapping classRequestMapping = AnnotationUtils.findAnnotation(controllerClazz, RequestMapping.class);
if (classRequestMapping != null) {
    controllerRequestMappingValues = classRequestMapping.value();
}

if (controllerRequestMappingValues.length == 0) {
    controllerRequestMappingValues = new String[1];
    controllerRequestMappingValues[0] = "";
}
return controllerRequestMappingValues;
   }
 
Example 7
Source File: RequestMappingInfoHandlerMappingTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
	RequestMapping annot = AnnotationUtils.findAnnotation(method, RequestMapping.class);
	if (annot != null) {
		return new RequestMappingInfo(
			new PatternsRequestCondition(annot.value(), getUrlPathHelper(), getPathMatcher(), true, true),
			new RequestMethodsRequestCondition(annot.method()),
			new ParamsRequestCondition(annot.params()),
			new HeadersRequestCondition(annot.headers()),
			new ConsumesRequestCondition(annot.consumes(), annot.headers()),
			new ProducesRequestCondition(annot.produces(), annot.headers()), null);
	}
	else {
		return null;
	}
}
 
Example 8
Source File: ApiRequestMappingHandlerMapping.java    From AthenaServing with Apache License 2.0 6 votes vote down vote up
/**
 * 创建匹配条件
 *
 * @param clazz
 * @return
 */
private static RequestCondition<ApiVersionCondition> createCondition(Class<?> clazz) {
    RequestMapping classRequestMapping = AnnotationUtils.findAnnotation(clazz, RequestMapping.class);
    if (classRequestMapping == null) {
        return null;
    }
    StringBuilder mappingUrlBuilder = new StringBuilder();
    if (classRequestMapping.value().length > 0) {
        mappingUrlBuilder.append(classRequestMapping.value()[0]);
    }
    String mappingUrl = mappingUrlBuilder.toString();
    if (!mappingUrl.contains("{version}") || !mappingUrl.contains("{v}")) {
        return null;
    }
    ApiVersion apiVersion = AnnotationUtils.findAnnotation(clazz, ApiVersion.class);
    return apiVersion == null ? new ApiVersionCondition(1) : new ApiVersionCondition(apiVersion.value());
}
 
Example 9
Source File: AbstractSpringmvcAction.java    From zxl with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public AbstractSpringmvcAction() {
	super();
	try {
		this.clazz = ((Class<T>) ReflectUtil.getParameterizedType(getClass()));
		RequestMapping mapping = getClass().getAnnotation(RequestMapping.class);
		this.mapping = mapping.value()[0];
	} catch (NullPointerException nullPointerException) {
		LogUtil.error(LOGGER, "Instantiation error", nullPointerException);
	}
}
 
Example 10
Source File: JsonHandlerExceptionResolver.java    From sca-best-practice with Apache License 2.0 5 votes vote down vote up
private void buildExceptionMetadata(ExceptionMetadata exceptionMetadata, Object handler,
                                    HttpServletRequest request) {
    if (handler != null && HandlerMethod.class.isAssignableFrom(handler.getClass())) {
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Class<?> beanType = handlerMethod.getBeanType();
        String methodName = handlerMethod.getMethod().getName();
        RequestMapping controllerRequestMapping = beanType.getDeclaredAnnotation(RequestMapping.class);
        String classMapping = "";
        if (controllerRequestMapping != null) {
            classMapping = controllerRequestMapping.value()[0];
        }
        RequestMapping methodRequestMapping = handlerMethod.getMethodAnnotation(RequestMapping.class);
        String methodMapping = "";
        if (methodRequestMapping != null) {
            methodMapping = methodRequestMapping.value()[0];
        }
        if (!methodMapping.startsWith("/")) {
            methodMapping = "/" + methodMapping;
        }
        exceptionMetadata.setHandlerMethod(true);
        exceptionMetadata.setBeanType(beanType);
        exceptionMetadata.setMethodName(methodName);
        exceptionMetadata.setClassMapping(classMapping);
        exceptionMetadata.setMethodMapping(methodMapping);
        exceptionMetadata.setParameterMap(request.getParameterMap());
    } else {
        exceptionMetadata.setHandlerMethod(false);
    }
}
 
Example 11
Source File: JsonHandlerExceptionResolver.java    From everyone-java-blog with Apache License 2.0 5 votes vote down vote up
private void logException(Object handler, Exception exception, Map<String, String[]> parameterMap) {
    if (handler != null && HandlerMethod.class.isAssignableFrom(handler.getClass())) {
        try {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Class<?> beanType = handlerMethod.getBeanType();
            String methodName = handlerMethod.getMethod().getName();
            RequestMapping controllerRequestMapping = beanType.getDeclaredAnnotation(RequestMapping.class);
            String classMapping = "";
            if (controllerRequestMapping != null) {
                classMapping = controllerRequestMapping.value()[0];
            }
            RequestMapping methodRequestMapping = handlerMethod.getMethodAnnotation(RequestMapping.class);
            String methodMapping = "";
            if (methodRequestMapping != null) {
                methodMapping = methodRequestMapping.value()[0];
            }
            if (!methodMapping.startsWith("/")) {
                methodMapping = "/" + methodMapping;
            }
            Logger logger = LoggerFactory.getLogger(beanType);
            logger.error("RequestMapping is:");
            logger.error(classMapping + methodMapping);
            logger.error("HandlerMethod is:");
            logger.error(beanType.getSimpleName() + "." + methodName + "()");
            logger.error("ParameterMap is:");
            logger.error(JsonUtils.toJson(parameterMap), exception);
        } catch (Exception e) {
            LOGGER.error(handler + " execute failed.", exception);
        }
    } else {
        LOGGER.error(handler + " execute failed.", exception);
    }
}
 
Example 12
Source File: DefaultAnnotationHandlerMapping.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Register all handlers specified in the Portlet mode map for the corresponding modes.
 * @throws org.springframework.beans.BeansException if the handler couldn't be registered
 */
protected void detectHandlers() throws BeansException {
	ApplicationContext context = getApplicationContext();
	String[] beanNames = context.getBeanNamesForType(Object.class);
	for (String beanName : beanNames) {
		Class<?> handlerType = context.getType(beanName);
		RequestMapping mapping = context.findAnnotationOnBean(beanName, RequestMapping.class);
		if (mapping != null) {
			// @RequestMapping found at type level
			String[] modeKeys = mapping.value();
			String[] params = mapping.params();
			boolean registerHandlerType = true;
			if (modeKeys.length == 0 || params.length == 0) {
				registerHandlerType = !detectHandlerMethods(handlerType, beanName, mapping);
			}
			if (registerHandlerType) {
				AbstractParameterMappingPredicate predicate = new TypeLevelMappingPredicate(
						params, mapping.headers(), mapping.method());
				for (String modeKey : modeKeys) {
					registerHandler(new PortletMode(modeKey), beanName, predicate);
				}
			}
		}
		else if (AnnotationUtils.findAnnotation(handlerType, Controller.class) != null) {
			detectHandlerMethods(handlerType, beanName, mapping);
		}
	}
}
 
Example 13
Source File: OpenFeignSpringMvcContract.java    From summerframework with Apache License 2.0 5 votes vote down vote up
@Override
protected void processAnnotationOnMethod(MethodMetadata data, Annotation methodAnnotation, Method method) {
    if (!RequestMapping.class.isInstance(methodAnnotation)
        && !methodAnnotation.annotationType().isAnnotationPresent(RequestMapping.class)) {
        return;
    }

    RequestMapping methodMapping = findMergedAnnotation(method, RequestMapping.class);

    RequestMethod[] methods = methodMapping.method();
    if (methods.length == 0) {
        methods = new RequestMethod[] {RequestMethod.GET};
    }
    checkOne(method, methods, "method");
    data.template().method(methods[0].name());

    checkAtMostOne(method, methodMapping.value(), "value");
    if (methodMapping.value().length > 0) {
        String pathValue = emptyToNull(methodMapping.value()[0]);
        if (pathValue != null) {
            pathValue = resolve(pathValue);

            if (!pathValue.startsWith("/") && !data.template().toString().endsWith("/")) {
                pathValue = "/" + pathValue;
            }
            data.template().append(pathValue);
        }
    }

    parseProduces(data, method, methodMapping);

    parseConsumes(data, method, methodMapping);

    parseHeaders(data, method, methodMapping);

    data.indexToExpander(new LinkedHashMap<Integer, Param.Expander>());
}
 
Example 14
Source File: CommonHandlerExceptionResolver.java    From everyone-java-blog with Apache License 2.0 5 votes vote down vote up
private void logException(Object handler, Exception exception, Map<String, String[]> parameterMap) {
    if (handler != null && HandlerMethod.class.isAssignableFrom(handler.getClass())) {
        try {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Class<?> beanType = handlerMethod.getBeanType();
            String methodName = handlerMethod.getMethod().getName();
            RequestMapping controllerRequestMapping = beanType.getDeclaredAnnotation(RequestMapping.class);
            String classMapping = "";
            if (controllerRequestMapping != null) {
                classMapping = controllerRequestMapping.value()[0];
            }
            RequestMapping methodRequestMapping = handlerMethod.getMethodAnnotation(RequestMapping.class);
            String methodMapping = "";
            if (methodRequestMapping != null) {
                methodMapping = methodRequestMapping.value()[0];
            }
            if (!methodMapping.startsWith("/")) {
                methodMapping = "/" + methodMapping;
            }
            Logger logger = LoggerFactory.getLogger(beanType);
            logger.error("RequestMapping is:");
            logger.error(classMapping + methodMapping);
            logger.error("HandlerMethod is:");
            logger.error(beanType.getSimpleName() + "." + methodName + "()");
            logger.error("ParameterMap is:");
            logger.error(JsonUtils.toJson(parameterMap), exception);
        } catch (Exception e) {
            LOGGER.error(handler + " execute failed.", exception);
        }
    } else {
        LOGGER.error(handler + " execute failed.", exception);
    }
}
 
Example 15
Source File: VenusSpringMvcContract.java    From venus-cloud-feign with Apache License 2.0 4 votes vote down vote up
@Override
protected void processAnnotationOnMethod(MethodMetadata data,
                                         Annotation methodAnnotation, Method method) {
    if (!RequestMapping.class.isInstance(methodAnnotation) && !methodAnnotation
            .annotationType().isAnnotationPresent(RequestMapping.class)) {
        return;
    }

    RequestMapping methodMapping = findMergedAnnotation(method, RequestMapping.class);
    // HTTP Method
    RequestMethod[] methods = methodMapping.method();
    if (methods.length == 0) {
        methods = new RequestMethod[] { RequestMethod.GET };
    }
    checkOne(method, methods, "method");
    data.template().method(methods[0].name());

    // path
    checkAtMostOne(method, methodMapping.value(), "value");
    if (methodMapping.value().length > 0) {
        String pathValue = emptyToNull(methodMapping.value()[0]);
        if (pathValue != null) {
            pathValue = resolve(pathValue);
            // Append path from @RequestMapping if value is present on method
            if (!pathValue.startsWith("/")
                    && !data.template().toString().endsWith("/")) {
                pathValue = "/" + pathValue;
            }
            data.template().append(pathValue);
        }
    }

    // produces
    parseProduces(data, method, methodMapping);

    // consumes
    parseConsumes(data, method, methodMapping);

    // headers
    parseHeaders(data, method, methodMapping);

    data.indexToExpander(new LinkedHashMap<Integer, Param.Expander>());
}
 
Example 16
Source File: RoleResourceAspect.java    From disconf with Apache License 2.0 4 votes vote down vote up
/**
 * 判断当前用户对访问的方法是否有权限
 *
 * @param pjp            方法
 * @param requestMapping 方法上的annotation
 *
 * @return
 *
 * @throws Throwable
 */
@Around("anyPublicMethod() && @annotation(requestMapping) && !@annotation(com.baidu.dsp.common.annotation.NoAuth)")
public Object decideAccess(ProceedingJoinPoint pjp, RequestMapping requestMapping) throws Throwable {

    // 获取method上的url,若未标注value则默认为空字符串
    String[] values = requestMapping.value();
    String methodUrl = "";
    if (values.length != 0) {
        methodUrl = values[0];
    }

    String clsUrl = pjp.getTarget().getClass().getAnnotation(RequestMapping.class).value()[0];

    // 拼接method和class上标注的url
    if (!clsUrl.endsWith(RoleResourceConstant.URL_SPLITOR) &&
            !methodUrl.startsWith(RoleResourceConstant.URL_SPLITOR)) {
        clsUrl += RoleResourceConstant.URL_SPLITOR;
    }

    String urlPattarn = clsUrl + methodUrl;
    if (!urlPattarn.endsWith(RoleResourceConstant.URL_SPLITOR)) {
        urlPattarn += RoleResourceConstant.URL_SPLITOR;
    }

    if (noAuthCheckUrl != null && noAuthCheckUrl.contains(urlPattarn)) {

        LOG.info("don't need to check this url: " + urlPattarn);
    } else {

        // 获取method上标注的http method,若未标注method则默认为GET
        RequestMethod[] methods = requestMapping.method();
        RequestMethod methodType = RequestMethod.GET;
        if (methods.length != 0) {
            methodType = methods[0];
        }

        String urlInfo = urlPattarn + ", method:" + methodType.toString();

        // 获取用户角色
        Visitor visitor = ThreadContext.getSessionVisitor();
        if (visitor == null) {
            LOG.warn("No session visitor!");
            throw new AccessDeniedException("No session visitor! " + urlInfo);
        }
        Integer roleId = visitor.getRoleId();
        String visitorInfo = ", UserId:" + visitor.getId() + ", RoleId:" + roleId;

        Boolean isPriviledged = true;
        // 判断用户是否有权限访问方法
        if (!this.isMethodAccessible(urlPattarn, methodType, roleId)) {
            isPriviledged = false;
            throw new AccessDeniedException("Access Denied: " + urlInfo + visitorInfo);
        }
        LOG.info("Accessing URL:" + urlInfo + visitorInfo + ", Is priviledged:" + isPriviledged.toString());
    }

    Object rtnOb = null;

    try {
        // 执行方法
        rtnOb = pjp.proceed();
    } catch (Throwable t) {
        LOG.info(t.getMessage());
        throw t;
    }

    return rtnOb;
}
 
Example 17
Source File: WebInterceptor.java    From efo with MIT License 4 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws
        Exception {
    String url = request.getServletPath();
    InterceptorLevel level = InterceptorLevel.NONE;
    if (handler instanceof HandlerMethod) {
        AuthInterceptor interceptor = ((HandlerMethod) handler).getMethodAnnotation(AuthInterceptor.class);
        //注解到类上面的注解,无法直接获取,只能通过扫描
        if (Checker.isNull(interceptor)) {
            for (Class<?> type : EfoApplication.controllers) {
                RequestMapping mapping = type.getAnnotation(RequestMapping.class);
                if (Checker.isNotNull(mapping)) {
                    for (String path : mapping.value()) {
                        if (url.startsWith(path)) {
                            interceptor = type.getAnnotation(AuthInterceptor.class);
                            break;
                        }
                    }
                    break;
                }
            }
        }
        if (Checker.isNotNull(interceptor)) {
            level = interceptor.value();
        }
    }
    User user = (User) request.getSession().getAttribute(ValueConsts.USER_STRING);
    if (Checker.isNull(user)) {
        //读取token,自动登录
        Cookie cookie = HttpUtils.getCookie(ValueConsts.TOKEN_STRING, request.getCookies());
        if (Checker.isNotNull(cookie)) {
            user = userService.login(ValueConsts.EMPTY_STRING, ValueConsts.EMPTY_STRING, cookie.getValue(),
                    response);
            if (Checker.isNotNull(user)) {
                request.getSession().setAttribute(ValueConsts.USER_STRING, user);
            }
        }
    }
    if (level != InterceptorLevel.NONE) {
        boolean isRedirect = Checker.isNull(user) || (level == InterceptorLevel.ADMIN && user.getPermission() <
                2) || (level == InterceptorLevel.SYSTEM && user.getPermission() < 3);
        if (isRedirect) {
            response.sendRedirect(DefaultValues.SIGNIN_PAGE);
            return false;
        }
    }
    return true;
}
 
Example 18
Source File: SpringMvcContract.java    From raptor with Apache License 2.0 4 votes vote down vote up
@Override
protected void processAnnotationOnMethod(MethodMetadata data,
                                         Annotation methodAnnotation, Method method) {
    if (!RequestMapping.class.isInstance(methodAnnotation) && !methodAnnotation
            .annotationType().isAnnotationPresent(RequestMapping.class)) {
        return;
    }

    RequestMapping methodMapping = findMergedAnnotation(method, RequestMapping.class);
    // HTTP Method
    RequestMethod[] methods = methodMapping.method();
    if (methods.length == 0) {
        methods = new RequestMethod[]{RequestMethod.GET};
    }
    checkOne(method, methods, "method");
    data.template().method(methods[0].name());

    // path
    checkAtMostOne(method, methodMapping.value(), "value");
    if (methodMapping.value().length > 0) {
        String pathValue = emptyToNull(methodMapping.value()[0]);
        if (pathValue != null) {
            pathValue = resolve(pathValue);
            // Append path from @RequestMapping if value is present on method
            if (!pathValue.startsWith("/")
                    && !data.template().toString().endsWith("/")) {
                pathValue = "/" + pathValue;
            }
            data.template().append(pathValue);
        }
    }

    // produces
    parseProduces(data, method, methodMapping);

    // consumes
    parseConsumes(data, method, methodMapping);

    // headers
    parseHeaders(data, method, methodMapping);

    data.indexToExpander(new LinkedHashMap<Integer, Param.Expander>());
}
 
Example 19
Source File: LogOperationAspect.java    From GreenSummer with GNU Lesser General Public License v2.1 4 votes vote down vote up
private String extractOperationName(
    Method method) {
  try {
    final String operationName;
    RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
    GetMapping getMapping = method.getAnnotation(GetMapping.class);
    PostMapping postMapping = method.getAnnotation(PostMapping.class);
    PutMapping putMapping = method.getAnnotation(PutMapping.class);
    DeleteMapping deleteMapping = method.getAnnotation(DeleteMapping.class);
    PatchMapping patchMapping = method.getAnnotation(PatchMapping.class);
    LogOperation logOperation = method.getAnnotation(LogOperation.class);
    RequestMapping classrequestMapping = method.getDeclaringClass().getAnnotation(RequestMapping.class);
    String basicName = null;
    if (logOperation != null && logOperation.value() != null && logOperation.value().trim().length() > 0) {
      operationName = logOperation.value();
    } else {
      if (requestMapping != null && requestMapping.value() != null && requestMapping.value().length > 0) {
        basicName = requestMapping.value()[0];
      } else if (getMapping != null && getMapping.value() != null && getMapping.value().length > 0) {
        basicName = getMapping.value()[0];
      } else if (postMapping != null && postMapping.value() != null && postMapping.value().length > 0) {
        basicName = postMapping.value()[0];
      } else if (putMapping != null && putMapping.value() != null && putMapping.value().length > 0) {
        basicName = putMapping.value()[0];
      } else if (deleteMapping != null && deleteMapping.value() != null && deleteMapping.value().length > 0) {
        basicName = deleteMapping.value()[0];
      } else if (patchMapping != null && patchMapping.value() != null && patchMapping.value().length > 0) {
        basicName = patchMapping.value()[0];
      }
      if (basicName != null) {
        if (classrequestMapping != null && classrequestMapping.value() != null && classrequestMapping.value().length > 0) {
          operationName = classrequestMapping.value()[0] + basicName;
        } else {
          operationName = basicName;
        }
      } else {
        operationName = null;
      }
    }
    return operationName;
  } catch (Exception e) {
    log.error("Error extracting arguments from method", e);
    return null;
  }
}
 
Example 20
Source File: RoleResourceAspect.java    From disconf with Apache License 2.0 4 votes vote down vote up
/**
 * 判断当前用户对访问的方法是否有权限
 *
 * @param pjp            方法
 * @param requestMapping 方法上的annotation
 *
 * @return
 *
 * @throws Throwable
 */
@Around("anyPublicMethod() && @annotation(requestMapping) && !@annotation(com.baidu.dsp.common.annotation.NoAuth)")
public Object decideAccess(ProceedingJoinPoint pjp, RequestMapping requestMapping) throws Throwable {

    // 获取method上的url,若未标注value则默认为空字符串
    String[] values = requestMapping.value();
    String methodUrl = "";
    if (values.length != 0) {
        methodUrl = values[0];
    }

    String clsUrl = pjp.getTarget().getClass().getAnnotation(RequestMapping.class).value()[0];

    // 拼接method和class上标注的url
    if (!clsUrl.endsWith(RoleResourceConstant.URL_SPLITOR) &&
            !methodUrl.startsWith(RoleResourceConstant.URL_SPLITOR)) {
        clsUrl += RoleResourceConstant.URL_SPLITOR;
    }

    String urlPattarn = clsUrl + methodUrl;
    if (!urlPattarn.endsWith(RoleResourceConstant.URL_SPLITOR)) {
        urlPattarn += RoleResourceConstant.URL_SPLITOR;
    }

    if (noAuthCheckUrl != null && noAuthCheckUrl.contains(urlPattarn)) {

        LOG.info("don't need to check this url: " + urlPattarn);
    } else {

        // 获取method上标注的http method,若未标注method则默认为GET
        RequestMethod[] methods = requestMapping.method();
        RequestMethod methodType = RequestMethod.GET;
        if (methods.length != 0) {
            methodType = methods[0];
        }

        String urlInfo = urlPattarn + ", method:" + methodType.toString();

        // 获取用户角色
        Visitor visitor = ThreadContext.getSessionVisitor();
        if (visitor == null) {
            LOG.warn("No session visitor!");
            throw new AccessDeniedException("No session visitor! " + urlInfo);
        }
        Integer roleId = visitor.getRoleId();
        String visitorInfo = ", UserId:" + visitor.getId() + ", RoleId:" + roleId;

        Boolean isPriviledged = true;
        // 判断用户是否有权限访问方法
        if (!this.isMethodAccessible(urlPattarn, methodType, roleId)) {
            isPriviledged = false;
            throw new AccessDeniedException("Access Denied: " + urlInfo + visitorInfo);
        }
        LOG.info("Accessing URL:" + urlInfo + visitorInfo + ", Is priviledged:" + isPriviledged.toString());
    }

    Object rtnOb = null;

    try {
        // 执行方法
        rtnOb = pjp.proceed();
    } catch (Throwable t) {
        LOG.info(t.getMessage());
        throw t;
    }

    return rtnOb;
}