DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How To Build Web Service Using Spring Boot 2.x
  • Building REST API Backend Easily With Ballerina Language
  • Load-Balancing Minecraft Servers with Kong Gateway
  • The Principles of Planning and Implementing Microservices

Trending

  • Optimize Deployment Pipelines for Speed, Security and Seamless Automation
  • Simplify Authorization in Ruby on Rails With the Power of Pundit Gem
  • Java's Quiet Revolution: Thriving in the Serverless Kubernetes Era
  • Comparing SaaS vs. PaaS for Kafka and Flink Data Streaming
  1. DZone
  2. Data Engineering
  3. Databases
  4. An Introduction to JAX-RS Annotations (Part 1)

An Introduction to JAX-RS Annotations (Part 1)

This three-part series on JAX-RS annotations starts off with some of the simpler rules and annotations and their roles in the Java EE world.

By 
Alex Theedom user avatar
Alex Theedom
·
Aug. 28, 17 · Tutorial
Likes (11)
Comment
Save
Tweet
Share
42.3K Views

Join the DZone community and get the full member experience.

Join For Free

The JAX-RS API forms an important part of the Java EE platform's commitment to providing standards-driven technology. The ubiquitous nature of the Internet and that recent increasing interest in the microservice architecture has put more focus on small, scalable, autonomous services and their interoperability. The principal methodology used to allow microservices to communicate with each other and the ‘outside world’ is REST and its use in developing RESTful APIs. The technology that Java EE provides for this is the JAX-RS: Java API for RESTful Web Services.

The Goals of JAX-RS

The goals of the JAX-RS API are:

  • POJO-based: To provide a collection of classes/interfaces and associated annotations to be used with POJOs so as to expose them as Web resources.
  • HTTP-centric: To use HTTP as the underlying network protocol and provide a clear mapping between HTTP and URI elements and the corresponding API classes and annotations.
  • Format independence: To be applicable to a wide variety of HTTP entity body content types and provide the necessary pluggability to allow additional types to be added.
  • Container independence: To ensure that artifacts using the API are deployable in a range of Web servers.
  • Inclusion in Java EE: To allow Java EE features and components to be used within a Web resource class.

Overview of JAX-RS Annotations

Annotations in the JAX-RS API are used to provide meta-data around the web resource. A typical example is to use the @GET annotation with the @Path annotation to identify the method that should handle a GET request to the specified URI in the @Path annotation.

What follows is a very quick overview of the annotations available to mark the methods and classes used to construct web resources. This is not an exhaustive list, there are a few more annotations in the JAR-RS arsenal, however, as the majority of the work of JAX-RS is in configuration and handling web resources, this is where you will find the majority of the API's annotations put to use.

This is the first in a three-part series looking at JAX-RS annotations.

Part two covers:

  • The @Path Annotation and @PathParam
  • The @QueryParamter Annotation
  • The @Produces Annotation
  • The @Consumes Annotation

Part three covers:

  • The @FormParam Annotation
  • The @MatrixParam Annotation
  • The @CookieParam Annotation
  • The @HeaderParam Annotation
  • The @Provider Annotation

Let’s get started.

The @ApplicationPath Annotation

Let’s start at the top of the trees with the @ApplicationPath annotation:

@ApplicationPath("/api")
public class RESTConfig extends Application {}


This is where you start defining the URI to your resources. Here we are saying that all our resources are to be found at the root /api. The URL should look something like this: http://localhost:8080/webcontext/api/ where webcontext is the name of your application.

The @Path Annotation

Next, comes the URI path to the resource. In a bookshop application, this might be /books/.

@Path("/books")
public class BookResource {}


Now, the URI to the book resource is /api/books and the URL would be http://localhost:8080/webcontext/api/books. It is the convention to name the resource as a noun and in the plural.

Once the path to our resource has been defined the individual resource method are configured for the HTTP method and context type. This is where the fun begins.

There is an annotation for each of the HTTP methods.

The @GET HTTP Method Annotation

Methods annotation with the @GET annotation respond to HTTP get requests.

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getAllBooks() {
    List<Book> books = BookRepository.getAllBooks(); // queries database for all books
    GenericEntity<List<Book>> list = new GenericEntity<List<Book>>(books) {};
    return Response.ok(list).build();
}


Note that the GenericEntity wrapper is used to maintain the generic type of the List as Book.

The @POST HTTP Method Annotation

Methods annotated @POST respond to POST method requests.

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response saveBook(Book book) {
    book = bookRepository.saveBook(book);
    return Response.ok(book).build();
}


The POST HTTP method is commonly used to create a resource. This example code persists the new book object in the database.

The @PUT HTTP Method Annotation

The @PUT annotation is used for updating a record and method annotated this way respond to an HTTP PUT request.

@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response updateBook(Book book) {
    book = bookRepository.updateBook(book);
    return Response.ok(book).build();
}


The @DELETE HTTP Method Annotation

Methods annotated @DELETE are expected to delete a resource.

@DELETE
@Path("{isbn}")
@Produces(MediaType.APPLICATION_JSON)
public Response deleteBook(@PathParam("isbn") String isbn) {
    Book book = bookRepository.deleteBookByIsbn(isbn);
    return Response.ok(book).build();
}


Usually, the resource or its id is passed to the resource method parameter from the URI variable as you can see in this example.

The @OPTIONS HTTP Method Annotation

Methods annotated with @OPTIONS respond to HTTP Option requests.

@OPTIONS
public Response preflight() {
    return Response.ok().header("Allow", true).build();
}


The options method is used as a request when the client wishes to make a complex HTTP request to a different domain. It is done in order to determine if the client is allowed to make the request or not.

The @HEAD HTTP Method Annotation

The HTTP HEAD method is identical to HTTP GET method except that the server mustn’t respond with a body in the response.

@HEAD
public Response headsUp() {
    return Response.ok().build();
}


This method is to obtain meta-data regarding the entity without sending back the entity body itself.

Code Repository

The source code for this article is in my GitHub repository. Code for all my articles is in the ReadLearnCode Articles repository.

What Next?

That is it for part one, coming up next is part two where you will learn more about the annotations used to make RESTful web endpoints.

Further Reading

I have published more articles about JAX-RS which I hope you find interesting:

  • JAX-RS Resource Entities is an article about creating resource entities
  • Ever wondered what @javax.ws.rs.core.Context annotation is all about?
  • Learn more about @Consumes and @Produces annotations, and finally
  • You cannot write robust endpoints without knowing about bean validation failure management
Annotation Database Java EE Web Service Requests

Published at DZone with permission of Alex Theedom, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How To Build Web Service Using Spring Boot 2.x
  • Building REST API Backend Easily With Ballerina Language
  • Load-Balancing Minecraft Servers with Kong Gateway
  • The Principles of Planning and Implementing Microservices

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!