问题
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