Wednesday Apr 22, 2009

Jersey aplication sharing Grizzly with static content and servlets

I was asked the question some time ago by one of my colleges here at SUN, and the same question was asked again recently at our user mailing list: "I want to run Jersey based application on Grizzly web server, but i want to also run another servlet from there, and possibly also serve some static content using the very same Grizzly sever instance. How do i do that?"

The answer is as simple as follows. Having imported

import com.sun.grizzly.http.embed.GrizzlyWebServer;
import com.sun.grizzly.http.servlet.ServletAdapter;
import com.sun.jersey.spi.container.servlet.ServletContainer;

You can just use:

        // static content is linked from here
        GrizzlyWebServer gws = new GrizzlyWebServer(8080, "/var/www");

        // Jersey web resources
        ServletAdapter jerseyAdapter = new ServletAdapter();
        jerseyAdapter.addInitParameter("com.sun.jersey.config.property.packages",
                "com.example");
        jerseyAdapter.setContextPath("/jersey");
        jerseyAdapter.setServletInstance(new ServletContainer());
        
        // Another non-Jersey servlet
        ServletAdapter simpleServletAdapter = new ServletAdapter();
        simpleServletAdapter.setContextPath("/simple");
        simpleServletAdapter.setServletInstance(new SimpleServlet());

        // register all above defined adapters
        gws.addGrizzlyAdapter(jerseyAdapter, new String[] {"/jersey"});
        gws.addGrizzlyAdapter(simpleServletAdapter, new String[] {"/simple"});

        // let Grizzly run
        gws.start();

Your Jersey resource classes are placed in com.example package, and will become accessible at http://localhost:8080/jersey base. Your static content for http://localhost:8080/ is taken from /var/www directory and a SimpleServlet will become available at http://localhost:8080/simple.

The only dependency you will need to include other than Jersey dependencies itself is

        <dependency>
            <groupId>com.sun.grizzly</groupId>
            <artifactId>grizzly-servlet-webserver</artifactId>
            <version>1.9.10</version>
        </dependency>

If you are interested in some more advanced scenarios, you can get inspired at Jean-Francois Arcand's blog post

About

Jakub Podlesak

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today