Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RESTful Java with JAX-RS 2 and Tomcat 9

I am testing RESTful service with JAX-RS 2. Below is my project and my classes.

enter image description here

@ApplicationPath("/test/*")
public class MyApplication extends Application {

    @Override
    public Set<Class<?>> getClasses() {
        Set<Class<?>> clazz = new HashSet<>();
        clazz.add(UserResource.class);
        System.out.println("getClass");
        return clazz;
    }

The resource class like:

@Path("/user")
public class UserResource {

    @GET
    @Produces("application/xml")
    public Response getUser() {
        return Response.created(URI.create("/dd")).build();
    }

    @GET
    public Response getDefaultUser() {
        System.out.println("getDefaultUser");
        return Response.created(URI.create("/dd")).build();
    }
}

When I test the service using http://localhost:8082/dt/test/user, I got 404 error.

like image 944
job wang Avatar asked Apr 12 '17 15:04

job wang


1 Answers

All you have is the JAX-RS API jar. This is only a "specifications" jar. It only has the interfaces and classes defined in the specification. But there is no engine behind this. The specification only contains the APIs that we can program against, but it's up to an implementation of the specification that provides the engine; a couple implementations being Jersey and RESTEasy.

That being said, JAX-RS is a part of the Java EE specification, so any fully Java EE compliant server will have this implementation as a part of it's internal library. But Tomcat is not a fully compliant Java EE server. It is only a servlet container, that implements only a small part of the EE specification, like servlets and JSP. So if you want to use JAX-RS in Tomcat, you should add an implementation.

One implementation you can use is Jersey. If you click the link, you can download the "Jersey x.x Bundle". Add these to your project, and it should work.

If you're working with Maven, then the minimum dependency you should have to run Jersey, is the following

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>${jersey.version}</version>
    <!-- latest version as of today is 2.32 -->
</dependency>

Update

Note: The latest version as of today (5/22/2021) is 3.0.2. With version 3.x, the namespacing for JAX-RS (and other EE APIs) has changed from javax to jakarta. So Tomcat 9 will not support this. You will have to use Tomcat 10, or you will have to use Jersey version 2.x.

like image 162
Paul Samsotha Avatar answered Oct 29 '22 21:10

Paul Samsotha