Why is this Simple JAX RS example not working?
Solution 1
You need to extend javax.ws.rs.core.Application (it can remain empty) and annotate it with @ApplicationPath("/ide"), then create a JAX-RS resource, ie, a class with an @Path("/hello") annotation. In this class, you'll just need to have your JAX-RS Resource Method annotated with @GET.
@ApplicationPath("/ide")
public class Rest extends Application { }
@Path("/hello")
public class HelloResource {
@GET
@Path("hello")
public String helloworld() {
return "Hello World!";
}
}
You can also take a look at this example: https://github.com/resteasy/Resteasy/tree/master/jaxrs/examples/oreilly-workbook/ex03_1
Solution 2
web.xml
<servlet>
<servlet-name>RestServlet</servlet-name>
<servlet-class>javax.ws.rs.core.Application</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RestServlet</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
Rest.java
public class Rest {
@GET
@Path("hello")
public String helloworld() {
return "Hello World!";
}
}
If you need, you can add
YourApplication.java
package playground;
import javax.ws.rs.core.Application;
...
public class YourApplication extends Application {
@Override
public Set<Class<?>> getClasses()
{
Set<Class<?>> yourResources = new HashSet<Class<?>>();
yourResources.add(InvoiceResource.class);
return yourResources;
}
}
Then
web.xml
<servlet>
<servlet-name>RestServlet</servlet-name>
<servlet-class>playground.YourApplication</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RestServlet</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
If you add @ApplicationPath("/api")
for YouApplication
, then web.xml shouldn't have servlet-mapping
.
Comments
-
Fagner Brack almost 2 years
I am trying to get working a simple JAX RS example, but I am failing to do so.
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>PLAYGROUND</display-name> <servlet-mapping> <servlet-name>playground.Rest</servlet-name> <url-pattern>/api/*</url-pattern> </servlet-mapping> </web-app>
Rest.java
package playground; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Application; public class Rest extends Application { @GET @Path("hello") public String helloworld() { return "Hello World!"; } }
Accessing
http://localhost/{warcontext}/api/hello
with the browser (GET) gives me 404 error statusIt is probably something very silly but I can't figure out.
Using: JBoss EAP 6.1.0 (Java EE 6)