2

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

/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。

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

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

4

1 回答 1

1

您可以将地图作为 aMap<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;
        }
    }
}

和一个小提琴

于 2012-11-22T11:43:06.793 回答