Jetty embed in Processing.org, static assets + POS

2019-06-13 04:40发布

问题:

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) {
  };


}

回答1:

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.

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;


void setup() {
    /* Configure the http server */
    Server server = new Server();
    SelectChannelConnector connector = new SelectChannelConnector();
    connector.setPort(8080);
    server.addConnector(connector);

    /* Resources */
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setDirectoriesListed(true);
    resourceHandler.setWelcomeFiles(new String[] { 
        "index.html"
    }
    );

    resourceHandler.setResourceBase(sketchPath("")+"pftf");
    ContextHandler resourceContext = new ContextHandler();
    resourceContext.setContextPath("/");
    resourceContext.setHandler(resourceHandler);


    /* Post API */
    PostHandler postHandler = new PostHandler();
    ContextHandler postContext = new ContextHandler();
    postContext.setContextPath("/post");
    postContext.setHandler(postHandler);

    ContextHandlerCollection contexts = new ContextHandlerCollection();
    contexts.setHandlers(new Handler[] { 
        resourceContext, postContext
    }
    );

    server.setHandler(contexts);


    /* Start the server (finally)  */

    try {
        server.start();
        server.join();
    } 
    catch(Exception e) {
        println("Could not start http server. Reason: " + e.toString());
    };
}


void printCard(String mtext) {
    println("Printing card with text: " + mtext);
}

Your PostHandler could look something like this:

public class PostHandler extends AbstractHandler
{
    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        response.setContentType("text/html;charset=utf-8");

        String stringParameter = request.getParameter("string");

        /* Check if the string parameter is there and not empty */
        if (stringParameter != null && !stringParameter.trim().equals("")) {

            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            response.getWriter().println("<h1>You sent me: " + stringParameter + "</h1>");

            println("Received a string via /post: " + stringParameter);

            printCard(stringParameter);
        } 
        else {
            // Parameter is missing
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST );
            baseRequest.setHandled(true);
            response.getWriter().println("<h1>Error: Missing string parameter</h1>");

            println("Missing string via /post.");
        }
    }
}