The requested route has not been mapped in Spark

Alex Rodriguez picture Alex Rodriguez · Sep 18, 2015 · Viewed 19.8k times · Source

I want to do something to sign up users with spark+java+hibernate+postgres

This is my code:

post("/registrar", (request, response) -> {
        EntityManagerFactory emf = Persistence.
         createEntityManagerFactory("compradorcitoPU");
         EntityManager em = emf.createEntityManager();em.getTransaction().begin();
         em.persist(u);
         em.getTransaction().commit();
         em.close(); return null; });

but this error shows up:

INFO spark.webserver.MatcherFilter - The requested route [/registrarnull] has not been mapped in Spark

Answer

Howard Roark picture Howard Roark · Sep 26, 2015

I had a similar problem. The items I'm returning are large and I wanted to write them out over stream. So, my software looked like this:

    post("/apiserver", "application/json", (request, response) -> {
        log.info("Received request from " + request.raw().getRemoteAddr());
        ServerHandler handler = new ServerHandler();
        return handler.handleRequest(request, response);
    });

In my handler, I got the raw HttpResponse object, opened its OutputStream and wrote over it like so:

    ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(response.raw().getOutputStream(), records);

Since I knew I had written over the OutputStream what the caller had asked for at that point (or an error), I figured I could just return null. My program worked fine. Spark would route the request to my handler as expected. And, since I was writing over the raw OutputStream, I was getting back what was expected on the client side. But, I kept seeing the message '/apiserver route not defined' in my server logs.

In looking at the Spark documentation, it says:

The main building block of a Spark application is a set of routes. A route is made up of three simple pieces:

A verb (get, post, put, delete, head, trace, connect, options)

A path (/hello, /users/:name)

A callback (request, response) -> { }

Obviously Spark does not know what you wrote over the raw HttpResponse and as a web-server, you should be providing some response to callers. So, if your response is null, you haven't fulfilled the requirements of providing a callback and you get the error that there's no map found even if Spark behaved as expected otherwise. Just return a response (null is not a response, "200 OK" is) and the error will go away.

[Edit] Spelling and grammar.