02. Simple application

Thanks to Java Brains.

1. Application and resources classes


Let's create a new package under the src/main/java folder, for instance, "org.ximodante,jaxrs"




and create 2 classes:

  • MyApp that extends Application that looks for the resources assigned to it
  • MyResource that is a resource of the application 

2.1 Application  class

  • Should extend javax.ws.rs.core.Application (that is an abstract class)
  • Is annotated by java.ws.rs.ApplicationPath if it is required an additional path. In this case the path is "firstapi"
The call to the application should begin with http://localhost:8080/Jaxrs02/firstapi in order to use any of its resources!


1
2
3
4
5
6
7
8
9
package org.ximodante.jaxrs;

import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;

@ApplicationPath("firstapi")
public class MyApp extends Application{

}

2.2 Resources  class

Is annotated by:
  • javax.ws.rs.Path (this is an indication of a class resource and that belongs to the application class)
  • javax.ws.rs.GET (in a method, indicating a GET request to the URL) 
  • javax.ws.rs.Produces (in a method to indicate the type of output). This type of output can be typified by the values of javax.ws.rs.core.MediaType; in this case "TEXT_PLAIN"
  • Optionally javax.inject.Singleton (if we want it to be a singleton. It can cause some problems)



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
package org.ximodante.jaxrs;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("test01")
public class MyResource {
 
 @GET
 @Produces (MediaType.TEXT_PLAIN)
 public String testMethod() {
  return "I think this works!";
 }
}


Now if we right-click the project and "Run As - Run on Server" and write this URL to the browser

http://localhost:8080/Jaxrs02//firstapi/test01



2. More about the application class and the resources class

The application class is an abstract class (javax.ws.rs.core.Application) has some unimplemented methods:

  • Set<Class> getClasses() : Return a set of the Resources classes assigned to the aplication. If we return an empty set, then no resource classes will be used in the application.

The resources class can be annotated by a javax.inject.Singleton annotation. If we include an attribute in the resource class that has this annotation, then the variable is only initialized once. This idea can be used for instance to create a counter and each time the resources is called the variable is incremented. If no @Singleton annotation is present, the variable is initialized at every call.

Comentarios

Entradas populares de este blog

03. Param annotations, and param converters

04. MessageBodyReaders and MessageBodyWriters. Custom Media Types

08. Filters & Interceptors. CDI . Conclusions