thebiggestlebowski February 2016

sparkjava routing conflict: static files and default exception handler

I have a json webservice which I want to only return json. Right now, when a user requests a resource which doesn't exist, they get an html 404 response from sparkjava engine.

I tried returning 404 json response as follows:

  1. using sparkjava, I initialize my static files.

    externalStaticFileLocation("/my/static/file/path");

  2. I set up my application endpoints.

  3. The last endpoints I set up are my 404 handlers. Basically, if the URL wasn't matched by 1 or 2 above, then assume 404 like so:

    get("/*", BaseWebApp::notFound, new JsonTransformer());
    put("/*", BaseWebApp::notFound, new JsonTransformer());
    post("/*", BaseWebApp::notFound, new JsonTransformer());
    delete("/*", BaseWebApp::notFound, new JsonTransformer()); 
    

This does not work. When I request a static file, I get my json 404 response. The sparkjava documentation states:

Routes are matched in the order they are defined. The first route that 
matches the request is invoked.

I would have thought that since I initialized my static files before the 404 endpoints that I would not get a 404 response. This question is similar and unfortunately is not answered: https://groups.google.com/forum/#!searchin/sparkjava/static/sparkjava/2SQFmSao2t8/ucfbM-QDCaMJ.

Answers


Laercio February 2016

Why would you declare such a route? It would make sense only if it was a before/after filter.


thebiggestlebowski February 2016

My web application serves static html files and it also has json webservice endpoints. I separated out my namespace so that all json webservices are prefixed with "v1". Now, my json 404 matches "/v1/*". I get a json 404 when they try to request a nonexistent json endpoint. The application returns html 404 otherwise.

This is better than what I originally had since there are cases where I should return an html 404.

Post Status

Asked in February 2016
Viewed 3,546 times
Voted 7
Answered 2 times

Search




Leave an answer