Wednesday, August 7, 2013

having trouble with jersey 2.0 and servlet 3.0? you need jersey-core-servlet!

a subtle problem

I just came across this with some example code I'm working on, and the problem is easy to miss.

Let's say you want to use the JAXRS @ApplicationPath annotation for your Jersey application, and you don't want to use a web.xml file anymore, i.e. you want to programmatically define your servlet using Servlet 3.0 mechanisms. You have everything set up just like you've seen in all of the examples online, you run mvn jetty:run, and... Nothing.

two dependencies

There are two dependencies that serve similar purposes; adapting Jersey 2.0's Application class to a servlet instance. One of them includes compatibility for Servlet 2.x, and the other doesn't:

You'd think that this just means one has the ability to support Servlet 2.x and the other doesn't. In my experience, the case is that automatic Servlet 3.0 hooks won't actually work with jersey-container-servlet-core at all; it only works using jersey-container-servlet. Amusingly, the comment in the pom that is generated by the Jersey archetype (not the Grizzly one) is, at least in my mind, equally misleading:

In my mind, it makes more sense for this to say:

proof

I set up a very basic example of this behavior that you can feel free to mess around with if you like. The following two classes make up what is just about the most basic example for a Jersey app (though I use ResourceConfig instead of Application just because I like its flexibility better):

To make this work, here's the pom we're going to use. In comments in the dependencies section, you can see which line you need to comment to experience the problem:

simple, but not so obvious, solution

Hopefully this helps you. This actually had me scratching my head (which means grinding my teeth as I gradually type harder) for the better part of a day before I realized I'd been bamboozled by similar dependencies.

5 comments:

  1. Thanks for this. I wasted a lot of time on this issue before finding your post.

    ReplyDelete
    Replies
    1. Glad I could help :)

      Often times my process is exactly that: if I've wasted a lot of time on a problem but found an answer, someone else is probably wasting time on it too and could use some help.

      Delete
  2. You're awesome. This drove me nuts until I came across your post. Thanks!!

    ReplyDelete
    Replies
    1. You're awesome for giving me some feedback; thanks! Same here; I was losing my mind on this for hours.

      Delete
  3. Hi,
    Can you please share the actual project or point me to git, i just cant get it to work.
    thanks

    ReplyDelete