The correct way to pass data to/from a java HttpHandler class for java HttpServer class

删除回忆录丶 提交于 2019-12-12 03:42:14

问题


I have a java HttpHandler that I am using to test an application. In the HttpHandler each http request is handled in a separate thread and is passed the HttpExchange. But I need to access data from the main thread and class (the one that setup the HttpServer and HttpHandler) so that HttpHandler can send back the correct response for the current test being run. How is the best way to get this data passed in or accessible by the HttpHandler class? I cannot add another parameter to the HttpHandler#handle since that is defined by the HttpHandler & used by the HttpServer, and I can not access none static methods in the main class. I will also need to push messages from the HttpHandler back to the main class to log.

Thanks

A sample of my code:

class RequestHandler implements HttpHandler {

    @Override
    public void handle(HttpExchange exchange)
     {
        // do a bunch of stuff with the request that come in.
    }
}


public class MainClass
{
    public static void main(String[] args)
    {
        HttpServer server;
        ExecutorService excutor;
        InetSocketAddress addr = new InetSocketAddress(ipAdd, ipPort);
        server = HttpServer.create(addr, 0);
        server.createContext("/", new RequestHandler());
        excutor = Executors.newCachedThreadPool();
        server.setExecutor(excutor);
        server.start();
       // do a bunch of stuff that uses the server
    }

回答1:


From the comments you say that you are constructing the handlers yourself. A typical way that you can inject objects into the handlers is just to pass them in as arguments to the constructor.

For example:

public class RequestHandler implements HttpHandler {

    private final Object someObject;

    public RequestHandler(Object someObject) {
        // there is an implied super() here
        this.someObject = someObject;
    }

    public void handle(HttpExchange exchange) throws IOException {
       ...
       // you can then use someObject here
       ...
    }
}

Then you can pass in the object into your handler like:

server.createContext("/", new RequestHandler(someObject));

In terms of passing information around between handlers, you should be able to use the HttpExchange.setAttribute(...) method to do this. That is a typical way. I'd suggest using attribute names that start with "_" to differentiate them from HTTP attributes.



来源:https://stackoverflow.com/questions/11655720/the-correct-way-to-pass-data-to-from-a-java-httphandler-class-for-java-httpserve

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!