简体   繁体   English

为com.sun.net.httpserver.HttpServer(Java)创建动态上下文

[英]Create dynamically contexts for com.sun.net.httpserver.HttpServer (Java)

I need to handle HTTP requests using com.sun.net.httpserver.HttpServer which requests are triggered by the following URL schema: 我需要使用com.sun.net.httpserver.HttpServer处理HTTP请求,请求由以下URL模式触发:

http://somehost:9000/<var>/<service>

<var> is a parameter which is passed to the <service> <var>是传递给<service>

<service> is a predefined service that the server provides <service>是服务器提供的预定义服务

The problem is that the context path is not known at compile time (because of the <var> ) so I can not just call createContext(String path, HttpHandler handler) . 问题是上下文路径在编译时是未知的(因为<var> )所以我不能只调用createContext(String path, HttpHandler handler) How can I bind this kind of 'dynamic' context to a specific HttpHandler instance? 如何将这种“动态”上下文绑定到特定的HttpHandler实例?

You can handle "/" and adapt the handler, something like this: 你可以处理“/”并调整处理程序,如下所示:

createContext("/", new HttpHandler(){
    @Override
    void handle(final HttpExchange exchange) throws IOException {
         // use getRequestURI()
    }
});

see also HttpExchange#getRequestURI() 另见HttpExchange#getRequestURI()

I know this is a very old thread, but for anyone who finds it, I hope my answer will help. 我知道这是一个非常古老的主题,但对于任何找到它的人,我希望我的回答会有所帮助。

I was recently creating a similar server where I needed a URL handler for the form /person/[id]/[location] where "id" and "location" were variable values. 我最近创建了一个类似的服务器,我需要一个表单/ person / [id] / [location]的URL处理程序,其中“id”和“location”是变量值。 But I also needed a /person handler. 但我还需要一个/人处理程序。

I'm sure there's documentation on this somewhere, but I discovered that creatContext will assign a handler to whatever it first recognizes. 我确定在某个地方有关于此的文档,但我发现creatContext将为其首先识别的任何内容分配处理程序。

What that means is that all I had to do was define a handler for "/person" and inside that handler, check for the [id] and [location] values. 这意味着我所要做的就是为“/ person”定义一个处理程序,并在该处理程序中检查[id]和[location]值。 If there were those values, the handler would do something different, if not, it would just do the /person handler. 如果有这些值,处理程序会做一些不同的事情,如果没有,它只会执行/ person处理程序。

I hope this helps! 我希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM