Java Code Examples for org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#getHandlerMethods()

The following examples show how to use org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#getHandlerMethods() . 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: RequestMappingService.java    From api-mock-util with Apache License 2.0 6 votes vote down vote up
public boolean hasApiRegistered(String api,String requestMethod){
    notBlank(api,"api cant not be null");
    notBlank(requestMethod,"requestMethod cant not be null");

    RequestMappingHandlerMapping requestMappingHandlerMapping = webApplicationContext.getBean(RequestMappingHandlerMapping.class);
    Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();
    for (RequestMappingInfo info : map.keySet()) {
        for(String pattern :info.getPatternsCondition().getPatterns()){
            if(pattern.equalsIgnoreCase(api)){ // 匹配url
                if(info.getMethodsCondition().getMethods().contains(getRequestMethod(requestMethod))){ // 匹配requestMethod
                    return true;
                }
            }
        }
    }

    return false;
}
 
Example 2
Source File: SpringMvcHomeModuleExtensionFactory.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
public static HomeModuleExtension create(String pathPrefix, Collection<RequestMappingHandlerMapping> mappings) {
	HomeModuleExtension ext = new HomeModuleExtension();

	for (RequestMappingHandlerMapping mapping : mappings) {
		Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods();
		for (RequestMappingInfo info : handlerMethods.keySet()) {
			Set<String> patterns = info.getPatternsCondition().getPatterns();
			for (String pattern : patterns) {
				if (pattern.equals("/error") || pattern.contains("*")) {
					continue;
				}

				if (pathPrefix == null) {
					ext.addPath(pattern);
				} else if (pattern.startsWith(pathPrefix)) {
					ext.addPath(pattern.substring(pathPrefix.length()));
				}
			}
		}
	}

	return ext;
}
 
Example 3
Source File: BasicBeanConfig.java    From spring-boot-start-current with Apache License 2.0 6 votes vote down vote up
@Override
public void onApplicationEvent ( ContextRefreshedEvent event ) {
	final RequestMappingHandlerMapping requestMappingHandlerMapping =
		applicationContext.getBean( RequestMappingHandlerMapping.class );
	final Map< RequestMappingInfo, HandlerMethod > handlerMethods =
		requestMappingHandlerMapping.getHandlerMethods();

	this.handlerMethods = handlerMethods;

	handlerMethods.keySet().forEach( mappingInfo -> {
		Map< Set< String >, Set< RequestMethod > > mapping = Collections.singletonMap(
			mappingInfo.getPatternsCondition().getPatterns() ,
			this.getMethods( mappingInfo.getMethodsCondition().getMethods() )
		);
		requestMappingInfos.add( mapping );
	} );

	requestMappingUris.addAll(
		handlerMethods.keySet()
					  .parallelStream()
					  .map( mappingInfo -> mappingInfo.getPatternsCondition().getPatterns() )
					  .collect( Collectors.toList() )
	);

}
 
Example 4
Source File: ZebraListener.java    From Zebra with MIT License 6 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
    //获取上下文
    ServletContext sc = servletContextEvent.getServletContext();
    ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);

    //获取Mapping(就是存放了所有的Controoler中@Path注解的Url映射)
    RequestMappingHandlerMapping mapping = ac.getBean(RequestMappingHandlerMapping.class);

    //遍历所有的handlerMethods(为了从mapping中取出Url,交给Zookeeper进行注册)
    Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods();
    for (RequestMappingInfo key : handlerMethods.keySet()) {
        String serviceName = key.getName();
        if(!StringUtils.isEmpty(serviceName)){
            //不等于空,则拿到了服务名称,则立即注册
            registry.register(serviceName,String.format("%s:%d",serverAddress,serverPort));
        }
    }
}
 
Example 5
Source File: ZebraListener.java    From Zebra with MIT License 6 votes vote down vote up
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
    //向注册中心销毁自己的服务信息

    //获取上下文
    ServletContext sc = servletContextEvent.getServletContext();
    //获取ac
    ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);

    //获取Mapping(就是存放了所有的Controoler中@Path注解的Url映射)
    RequestMappingHandlerMapping mapping = ac.getBean(RequestMappingHandlerMapping.class);
    //遍历所有的handlerMethods(为了从mapping中取出Url,交给Zookeeper进行注册)
    Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods();
    for (RequestMappingInfo key : handlerMethods.keySet()) {
        String serviceName = key.getName();
        if (!StringUtils.isEmpty(serviceName)) {
            logger.info("卸载服务:" + serviceName);
            //不等于空,表示找到了配置中心的服务地址,则拿到了服务名称,要进行立即注册
            registry.unRegister(serviceName, String.format("%s:%d", serverAddress, serverPort));
        }
    }
}
 
Example 6
Source File: CommonPageController.java    From Shiro-Action with MIT License 5 votes vote down vote up
/**
 * 获取 @RequestMapping 中配置的所有 URL.
 * @param keyword   关键字: 过滤条件
 * @return          URL 列表.
 */
@GetMapping("/system/urls")
@ResponseBody
public ResultBean getUrl(@RequestParam(defaultValue = "") String keyword) {
    RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
    // 获取url与类和方法的对应信息
    Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
    Set<UrlVO> urlSet = new HashSet<>();

    for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {

        // URL 类型, JSON 还是 VIEW
        String type = "view";
        if (isResponseBodyUrl(m.getValue())){
            type = "json";
        }

        // URL 地址和 URL 请求 METHOD
        RequestMappingInfo info = m.getKey();
        PatternsRequestCondition p = info.getPatternsCondition();
        // 一个 @RequestMapping, 可能有多个 URL.
        for (String url : p.getPatterns()) {
            // 根据 keyword 过滤 URL
            if (url.contains(keyword)) {

                // 获取这个 URL 支持的所有 http method, 多个以逗号分隔, 未配置返回 ALL.
                Set<RequestMethod> methods = info.getMethodsCondition().getMethods();
                String method = "ALL";
                if (methods.size() != 0) {
                    method = StringUtils.collectionToDelimitedString(methods, ",");
                }
                urlSet.add(new UrlVO(url, method, type));
            }
        }
    }
    return ResultBean.success(urlSet);
}
 
Example 7
Source File: MenuServiceImpl.java    From FEBS-Security with Apache License 2.0 5 votes vote down vote up
@Override
public List<Map<String, String>> getAllUrl(String p1) {
    RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
    //获取 url与类和方法的对应信息
    Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
    List<Map<String, String>> urlList = new ArrayList<>();
    for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : map.entrySet()) {
        RequestMappingInfo info = entry.getKey();
        HandlerMethod handlerMethod = map.get(info);
        PreAuthorize permissions = handlerMethod.getMethodAnnotation(PreAuthorize.class);
        String perms = "";
        if (null != permissions) {
            String value = permissions.value();
            value = StringUtils.substringBetween(value, "hasAuthority(", ")");
            perms = StringUtils.join(value, ",");
        }
        Set<String> patterns = info.getPatternsCondition().getPatterns();
        for (String url : patterns) {
            Map<String, String> urlMap = new HashMap<>();
            urlMap.put("url", url.replaceFirst("\\/", ""));
            urlMap.put("perms", perms);
            urlList.add(urlMap);
        }
    }
    return urlList;

}
 
Example 8
Source File: X7Env.java    From x7 with Apache License 2.0 5 votes vote down vote up
private static void getMapPaths() {
    RequestMappingHandlerMapping rmhp = getObject(RequestMappingHandlerMapping.class);
    if (rmhp != null) {
        Map<RequestMappingInfo, HandlerMethod> map = rmhp.getHandlerMethods();
        for (RequestMappingInfo info : map.keySet()) {
            String mapping = info.getPatternsCondition().toString().replace("[", "").replace("]", "");
            HandlerMethod hm = map.get(info);
            mappingMap.put(hm.getMethod(), mapping);
        }
    }
}
 
Example 9
Source File: IndexController.java    From newblog with Apache License 2.0 5 votes vote down vote up
@RequestMapping("getAllUrl")
@ResponseBody
public Set<String> getAllUrl(HttpServletRequest request) {
    Set<String> result = new HashSet<>();
    WebApplicationContext wc = (WebApplicationContext) request.getAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    RequestMappingHandlerMapping bean = wc.getBean(RequestMappingHandlerMapping.class);
    Map<RequestMappingInfo, HandlerMethod> handlerMethods = bean.getHandlerMethods();
    for (RequestMappingInfo rmi : handlerMethods.keySet()) {
        PatternsRequestCondition pc = rmi.getPatternsCondition();
        Set<String> pSet = pc.getPatterns();
        result.addAll(pSet);
    }
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
    return result;
}
 
Example 10
Source File: SpringMvcHomeModuleExtensionFactory.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
public static HomeModuleExtension create(RequestMappingHandlerMapping mapping) {
	HomeModuleExtension ext = new HomeModuleExtension();

	Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods();
	for (RequestMappingInfo info : handlerMethods.keySet()) {
		Set<String> patterns = info.getPatternsCondition().getPatterns();
		for (String pattern : patterns) {
			if (pattern.equals("/error"))
				continue;
			ext.addPath(pattern);
		}
	}

	return ext;
}
 
Example 11
Source File: PrivilegeRequestUrlService.java    From smart-admin with MIT License 4 votes vote down vote up
@PostConstruct
public void initAllUrl() {
    this.privilegeUrlDTOList.clear();

    RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
    //获取url与类和方法的对应信息
    Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
    map.forEach((info, handlerMethod) -> {
        //只对Rest 服务进行权限验证
        RestController restAnnotation = AnnotationUtils.findAnnotation(handlerMethod.getMethod().getDeclaringClass(), RestController.class);
        if (restAnnotation == null) {
            ResponseBody responseBody = handlerMethod.getMethod().getAnnotation(ResponseBody.class);
            if (responseBody == null) {
                return;
            }
        }
        //获取url的Set集合,一个方法可能对应多个url
        Set<String> patterns = info.getPatternsCondition().getPatterns();
        if (CollectionUtils.isEmpty(patterns)) {
            return;
        }
        String className = (String) handlerMethod.getBean();
        String methodName = handlerMethod.getMethod().getName();
        List<String> list = SmartStringUtil.splitConvertToList(className, "\\.");
        String controllerName = list.get(list.size() - 1);
        String name = controllerName + "." + methodName;

        ApiOperation apiOperation = handlerMethod.getMethod().getAnnotation(ApiOperation.class);
        String methodComment = null;
        if (apiOperation != null) {
            methodComment = apiOperation.value();
        } else {
            ApiModelProperty apiModelProperty = handlerMethod.getMethod().getAnnotation(ApiModelProperty.class);
            if (apiModelProperty != null) {
                methodComment = apiModelProperty.value();
            } else {
                methodComment = handlerMethod.getMethod().getName();
            }
        }
        Set<String> urlSet = this.getUrlSet(patterns);
        for (String url : urlSet) {
            PrivilegeRequestUrlVO privilegeUrlDTO = new PrivilegeRequestUrlVO();
            privilegeUrlDTO.setUrl(url);
            privilegeUrlDTO.setName(name);
            privilegeUrlDTO.setComment(methodComment);
            this.privilegeUrlDTOList.add(privilegeUrlDTO);
        }

    });
}
 
Example 12
Source File: Knife4jController.java    From yshopmall with Apache License 2.0 4 votes vote down vote up
/** @deprecated */
@Deprecated
private void initGlobalRequestMappingArray(WebApplicationContext wc, SwaggerExt swaggerExt) {
    if (this.globalHandlerMappings.size() == 0) {
        String parentPath = "";
        if (!StringUtils.isEmpty(swaggerExt.getBasePath()) && !"/".equals(swaggerExt.getBasePath())) {
            parentPath = parentPath + swaggerExt.getBasePath();
        }

        Map<String, HandlerMapping> requestMappings = BeanFactoryUtils.beansOfTypeIncludingAncestors(wc, HandlerMapping.class, true, false);
        Iterator<HandlerMapping> var5 = requestMappings.values().iterator();

        while(true) {
            HandlerMapping handlerMapping;
            do {
                if (!var5.hasNext()) {
                    return;
                }
                handlerMapping = var5.next();
            } while(!(handlerMapping instanceof RequestMappingHandlerMapping));
            RequestMappingHandlerMapping rmhMapping = (RequestMappingHandlerMapping)handlerMapping;
            Map<RequestMappingInfo, HandlerMethod> handlerMethods = rmhMapping.getHandlerMethods();
            for (RequestMappingInfo rmi : handlerMethods.keySet()) {
                PatternsRequestCondition prc = rmi.getPatternsCondition();
                Set<RequestMethod> restMethods = rmi.getMethodsCondition().getMethods();
                Set<String> patterns = prc.getPatterns();
                HandlerMethod handlerMethod = (HandlerMethod) handlerMethods.get(rmi);

                String url;
                Class clazz;
                Method method;
                for (Iterator<String> var15 = patterns.iterator(); var15.hasNext(); this.globalHandlerMappings.add(new RestHandlerMapping(parentPath + url, clazz, method, restMethods))) {
                    url = var15.next();
                    clazz = ClassUtils.getUserClass(handlerMethod.getBeanType());
                    method = ClassUtils.getMostSpecificMethod(handlerMethod.getMethod(), clazz);
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("url:" + url + "\r\nclass:" + clazz.toString() + "\r\nmethod:" + method.toString());
                    }
                }
            }
        }
    }

}
 
Example 13
Source File: PermissionService.java    From FlyCms with MIT License 4 votes vote down vote up
@Transactional
public boolean getSyncAllPermission(){
    RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
    //获取url与类和方法的对应信息
    Map<RequestMappingInfo,HandlerMethod> map = mapping.getHandlerMethods();
    List<String> datalist = new ArrayList<String>();
    List<String> newlist = new ArrayList<String>();
    for (RequestMappingInfo info : map.keySet()){
        //获取url的Set集合,一个方法可能对应多个url
        Set<String> patterns = info.getPatternsCondition().getPatterns();
        for (String url : patterns){
            Permission per=new Permission();
            String urlstr=info.getPatternsCondition().toString();
            //替换花括号和里面所有内容为*
            urlstr=urlstr.replaceAll("\\{([^\\}]+)\\}", "*");
            //替换前后中括号
            urlstr=urlstr.replaceAll("[\\[\\]]", "");
            // 只处理后台管理 action,其它跳过
            if (urlstr.startsWith("/system")) {
                per.setActionKey(urlstr);
                per.setController(map.get(info).getBean().toString());
                String str=per.getActionKey();
                String[] array=str.split("\\|\\|");
                for(String s:array){
                    if(s!=null){
                        if (!checkPermission(StringUtils.deleteWhitespace(s), per.getController())) {
                            per.setActionKey(StringUtils.deleteWhitespace(s));
                            SnowFlake snowFlake = new SnowFlake(2, 3);
                            per.setId(snowFlake.nextId());
                            int permissionId=permissionDao.addPermission(per);
                            if(!this.markAssignedPermissions(272835742965968896L,per.getId())){
                                //默认超级管理员组添加新的权限关联,272835742965968896为超级管理员组ID
                                groupDao.addGroupPermission(272835742965968896L,per.getId());
                            }
                        }
                        //添加当前Controller里所有的权限路径到list里
                        newlist.add(StringUtils.deleteWhitespace(s));
                    }
                }
            }
        }
    }

    //处理数据库多余的权限路径数据
    List<Permission> allList=this.getAllPermissions();
    for(Permission date : allList){
        datalist.add(date.getActionKey());
    }
    //检查并删除
    this.checkAndDeletePermission(newlist,datalist);
    return true;
}
 
Example 14
Source File: UserPermissionService.java    From FlyCms with MIT License 4 votes vote down vote up
@Transactional
public boolean getSyncAllPermission(){
    RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
    //获取url与类和方法的对应信息
    Map<RequestMappingInfo,HandlerMethod> map = mapping.getHandlerMethods();
    List<String> datalist = new ArrayList<String>();
    List<String> newlist = new ArrayList<String>();
    for (RequestMappingInfo info : map.keySet()){
        //获取url的Set集合,一个方法可能对应多个url
        Set<String> patterns = info.getPatternsCondition().getPatterns();
        for (String url : patterns){
            UserPermission per=new UserPermission();
            String urlstr=info.getPatternsCondition().toString();
            //替换花括号和里面所有内容为*
            urlstr=urlstr.replaceAll("\\{([^\\}]+)\\}", "*");
            //替换前后中括号
            urlstr=urlstr.replaceAll("[\\[\\]]", "");
            // 只处理后台管理 action,其它跳过
            if (!urlstr.startsWith("/system") || urlstr.startsWith("/ucenter")) {
                per.setActionKey(urlstr);
                per.setController(map.get(info).getBean().toString());
                String str=per.getActionKey();
                String[] array=str.split("\\|\\|");
                for(String s:array){
                    if(s!=null){
                        if (!checkPermission(StringUtils.deleteWhitespace(s), per.getController())) {
                            per.setActionKey(StringUtils.deleteWhitespace(s));
                            SnowFlake snowFlake = new SnowFlake(2, 3);
                            per.setId(snowFlake.nextId());
                            int permissionId=userPermissionDao.addPermission(per);
                        }
                        //添加当前Controller里所有的权限路径到list里
                        newlist.add(StringUtils.deleteWhitespace(s));
                    }
                }
            }
        }
    }

    //处理数据库多余的权限路径数据
    List<UserPermission> allList=this.getAllPermissions();
    for(UserPermission date : allList){
        datalist.add(date.getActionKey());
    }
    //检查并删除
    this.checkAndDeletePermission(newlist,datalist);
    return true;
}
 
Example 15
Source File: NodeServiceImpl.java    From java-trader with Apache License 2.0 4 votes vote down vote up
/**
 * 根据path找到并发现REST Controller
 */
public static NodeMessage controllerInvoke(RequestMappingHandlerMapping requestMappingHandlerMapping, NodeMessage reqMessage) {
    String path = ConversionUtil.toString(reqMessage.getField(NodeMessage.FIELD_PATH));
    //匹配合适的
    Object result = null;
    Throwable t = null;
    RequestMappingInfo reqMappingInfo=null;
    HandlerMethod reqHandlerMethod = null;
    Map<RequestMappingInfo, HandlerMethod> map = requestMappingHandlerMapping.getHandlerMethods();
    for(RequestMappingInfo info:map.keySet()) {
        List<String> matches = info.getPatternsCondition().getMatchingPatterns(path);
        if ( matches.isEmpty() ) {
            continue;
        }
        reqMappingInfo = info;
        reqHandlerMethod = map.get(info);
        break;
    }

    if ( reqMappingInfo==null ) {
        t = new Exception("Controller for "+path+" is not found");
        logger.error("Controller for "+path+" is not found");
    } else {
        MethodParameter[] methodParams = reqHandlerMethod.getMethodParameters();
        Object[] params = new Object[methodParams.length];
        try{
            for(int i=0;i<methodParams.length;i++) {
                MethodParameter param = methodParams[i];
                String paramName = param.getParameterName();
                params[i] = ConversionUtil.toType(param.getParameter().getType(), reqMessage.getField(paramName));
                if ( params[i]==null && !param.isOptional() ) {
                    throw new IllegalArgumentException("Method parameter "+paramName+" is missing");
                }
            }
            result = reqHandlerMethod.getMethod().invoke(reqHandlerMethod.getBean(), params);
        }catch(Throwable ex ) {
            if ( ex instanceof InvocationTargetException ) {
                t = ((InvocationTargetException)ex).getTargetException();
            }else {
                t = ex;
            }
            logger.error("Invoke controller "+path+" with params "+Arrays.asList(params)+" failed: "+t, t);
        }
    }
    NodeMessage respMessage = reqMessage.createResponse();
    if ( t!=null ) {
        respMessage.setErrCode(-1);
        respMessage.setErrMsg(t.toString());
    } else {
        respMessage.setField(NodeMessage.FIELD_RESULT, JsonUtil.object2json(result));
    }
    return respMessage;
}