Question

When do I need to include the following snippet in web.xml in order to activate Jersey?

<servlet>
    <servlet-name>Jersey App</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.company.rest</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

Is it App. Server dependent if Jersey is activated by default or needs this web.xml entry?

If an App. Server does not require the code above, can I configure the servlet-mapping path, like:

<servlet-mapping>
    <servlet-name>Jersey App</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>
Was it helpful?

Solution

I am just summarizing the Jersey 2.x docs sent by Bhesh in comment:

Servlet 2.x Container

(Java EE 5, Glassfish 2.x), you need to hook Jersey as a Servlet.

<servlet>
    <servlet-name>MyApplication</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        ...
    </init-param>
</servlet>
...
<servlet-mapping>
    <servlet-name>MyApplication</servlet-name>
    <url-pattern>/myApp/*</url-pattern>
</servlet-mapping>

or a Servlet Filter:

<filter>
    <filter-name>MyApplication</filter-name>
    <filter-class>org.glassfish.jersey.servlet.ServletContainer</filter-class>
    <init-param>
        ...
    </init-param>
</filter>
...
<filter-mapping>
    <filter-name>MyApplication</filter-name>
    <url-pattern>/myApp/*</url-pattern>
</filter-mapping>

Servlet 3.x Container

Descriptorless case

(Java EE 6, 7; Glassfish 3, 4)There is no need for web.xml configuration for the simplest case. Instead an custom ResourceConfig class is needed with @ApplicationPath annotation for configuration:

@ApplicationPath("resources")
public class MyApplication extends ResourceConfig {
    public MyApplication() {
        packages("org.foo.rest;org.bar.rest");
    }
}

Configuring with web.xml

<web-app version="3.0"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <servlet>
        <servlet-name>javax.ws.rs.core.Application</servlet-name>
    </servlet>

    <servlet-mapping>
        <servlet-name>javax.ws.rs.core.Application</servlet-name>
        <url-pattern>/myresources/*</url-pattern>
    </servlet-mapping>
</web-app>

In this case all the root resource classes (the classes annotated with @Path annotation) as well as any providers that are annotated with @Provider annotation packaged with the application will be automatically registered in the JAX-RS application.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top