将URL映射到最具体的上下文根

时间:2012-11-22 10:03:34

标签: java url data-structures tree

我有以下情况:
我想将传入的查询(我使用servlet过滤器来访问查询)映射到合适的应用程序。为此,我有一个表格,我将应用程序映射到他们的contextroots,例如:

/application1/             |  Application1 Rootcontext 
/application1/subcontext1  |  Application1 Subcontext 1  
/application1/subcontext2  |  Application1 Subcontext 2  
/application2/             |  Application2

所以当我查询路径/ application1 / subcontext1 / someotherpath时,我想得到Application1 Subcontext 1,当我有一个查询URL / application1 / sompath时,我想得到Application 1 Rootcontext。

我的第一个猜测是,我使用contextroots的映射(该URL的每个部分作为节点)构建某种树,然后拆分查询URL并向下走树以获得最具体的应用程序映射。

这是最好的解决方案吗,或者您对我的问题有任何其他建议吗?

1 个答案:

答案 0 :(得分:1)

您可以将地图设置为Map<String, ApplicationContext>,然后向后走,直到找到第一个非空拟合,而不是树和向前走。此代码应该让您大致了解如何执行此操作:

import java.util.HashMap;
import java.util.Map;

public class Main {
    public static final class ApplicationContext {
        private final String app;
        private final String ctx;

        public ApplicationContext(final String app, final String ctx) {
            this.app = app;
            this.ctx = ctx;
        }

        @Override
        public String toString() {
            return "ApplicationContext[" + app + "/" + ctx + "]";
        }
    }

    private static ApplicationContext ac(final String app, final String ctx) {
        return new ApplicationContext(app, ctx);
    }

    private static ApplicationContext getApplicationContext(final String url,
            final Map<String, ApplicationContext> urlMap) {
        String specificUrl = url;
        ApplicationContext result = null;
        while (specificUrl != null && result == null) {
            result = urlMap.get(specificUrl);
            specificUrl = shortenUrl(specificUrl);
        }

        return result;
    }

    public static void main(final String[] args) throws Exception {
        final Map<String, ApplicationContext> urlMap = new HashMap<String, ApplicationContext>();
        urlMap.put("/application1", ac("Application1", "Root"));
        urlMap.put("/application1/subcontext1", ac("Application1", "SubContext1"));
        urlMap.put("/application1/subcontext2", ac("Application1", "SubContext2"));
        urlMap.put("/application1/subcontext2/subcontext3", ac("Application1", "SubContext3"));
        urlMap.put("/application2", ac("Application2", null));

        System.out.println(getApplicationContext("/application1/", urlMap));
        System.out.println(getApplicationContext("/application1/abc", urlMap));
        System.out.println(getApplicationContext("/application1/subcontext2/abc", urlMap));
    }

    private static String shortenUrl(final String url) {
        final int index = url.lastIndexOf('/');
        if (index > 0) {
            return url.substring(0, index);
        }
        else {
            return null;
        }
    }
}

并为它fiddle