NanoHttpd / nanohttpd

Tiny, easily embeddable HTTP server in Java.

Home Page:http://nanohttpd.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to pass external objects to handlers?

sandrock opened this issue · comments

I am using nanolets to add a few API endpoints to an existing app. I can't find a way to pass an object to my various handlers.

I created handlers that extends DefaultStreamHandler but there is no way to have an object of mine in there.

I tried to use the session object to set something in it for use in the handlers but there is no extensibility!

@Override
public Response serve(IHTTPSession session) {
    session.setData("DataSource", this.dataSource); // I would like this to exist
    session.setData("UserContext", this.userContext); // I would like this to exist
    return super.serve(session);
}

Mapping don't allow giving a live instance of handler so I cannot set something in there.

this.httpServer.addRoute("/api/DoSomething", new SomethingHandler(dataSource, userContext)); // can't do that

How do you do anything within the handlers if you can't have references to important objects?

Can you take a look at #579 and see if it solves your problem?

Hey @BroHammie,

I noticed your PR #579 is related with #418. Your PR changes how handlers get instantiated.

Your fix looks okay. I will test that when it appears in a new build. Thank you.

I have done more research. It looks like PR #309 was about that thing but the requester cancelled the PR without explaining much why.

@brettlounsbury discovered that the initParameters are available in the UriResource instances. And that instance is available in the handlers. And UriResource has two methods initParameter that allow getting the initParameters! Despite a few hours of searching the last time, we failed at that time to find this.

Problem can be fixed on my side with this new info. Your PR #579 is nice too.

This important feature needs more documentation. I suggest adding a sample mapping in the nanolets demo. I would like to do it but I am not familiar enough with java projects.

Thanks @sandrock you are absolutely correct!