I'm trying to embed Jetty in a Processing Sketch. So far I made it working to serve static files (a html directory in the Sketch folder).
I want to react to one POST with a user input from one of the static pages.
As I have no knowledge on Jetty and coming from a PHP & Ruby (RoR) web programing background I am very confused with the way things go in Jetty.
I simply want something similar to routes where everything except e.g.
"localhost:8080/post?string=whatever"
is a static file.
The post?string=whatever should maybe trigger a function (in Processing) where the submitted String is handled.
I have been reading the Jetty docs a lot but couldn't figure out so far how to do it.
Thank you very much for any help!
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
String poststr;
void setup() {
Server server = new Server();
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(8080);
server.addConnector(connector);
ResourceHandler resource_handler = new ResourceHandler();
resource_handler.setDirectoriesListed(true);
resource_handler.setWelcomeFiles(new String[] {
"index.html"
}
);
resource_handler.setResourceBase(sketchPath("")+"pftf");
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[] {
resource_handler, new DefaultHandler()
}
);
server.setHandler(handlers);
try {
server.start();
server.join();
}
catch(Exception e) {
};
}
Yes, Jetty can be very confusing in the beginning, especially when you only want to do a couple of simple things (not necessarily full-blown web applications).
The key to making this work is to use a ContextHandler for each of your other handlers (e.g. ResourceHandler). You can tell the ContextHandler which context (i.e. URL) it should respond to. After making a ContextHandler for the ResourceHandler and your custom Handler (e.g. PostHandler) you have to put both in a ContextHandlerCollection (uff...), so your Server knows what contexts exist.
Your PostHandler could look something like this: