问题
I am testing RESTful service with JAX-RS 2. Below is my project and my classes.
@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.
回答1:
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 "JAX-RS 2.0 RI Bundle". Add these to your project, and it should work.
来源:https://stackoverflow.com/questions/43373733/restful-java-with-jax-rs-2-and-tomcat-9