user3310917
user3310917

Reputation: 425

Jetty and Jersey: How does everything fits together?

I am looking for using jersey with embedded Jetty for implementing web APIs for our service. I see code where ServletContextHandler , ServletHolder and all these classes are used to let Jetty know about the Jersey handlers. I am interested to know under the hood, like what happens when we compile this code, how jetty actually discovers the jersey handlers. I know that if I start reading the documentation, I will be able to figure out, however, looking for some quick links that covers this topic. Is there any such link?

Thanks.

Upvotes: 5

Views: 9987

Answers (1)

user3310917
user3310917

Reputation: 425

Jetty can act as a http server and also a servlet container who deals with the lifecycle of servlets (init, service, destroy) etc. A servlet is a java class that extends HttpServlet class and can override init, service, destroy methods etc. Once jetty receives a request whose URL matches with that of a servlet, it loads the servlet in memory (if not already there), calls service method, and keeps it in memory until it destroys it.

Jersey library has provided a standard way of writing RESTful APIs where classes are annotated with tags like say GET/POST etc and the URL. These classes are called resource classes. It has also provided a servlet whose name is ServletContainer to hook up with Jetty's servlet container, that intercepts Jetty's request to process servlet (like for any servlet request to jetty this is the one class, that receives the request first). What this servlet does is it examines the request, matches with the resource classes URL that it is informed about, and then transfers control to that method of that resource class (i think it uses reflection for this routing). Therefore, the resource classes are not servlet itself, but the ServletContainer class of jersey is the only servlet active in the system. The list of resource classes ServletContainer knows about is configured by this property called "com.sun.jersey.config.property.packages"
The benefit of using Jersey is implementing your REST APIs is you are using standard way of writing your code that you can deploy to any other standard servlet container if needed in future like tomcat, ...

Upvotes: 22

Related Questions