Java EE 7 Application Developer study materials
Java EE 7 Application Developer study resources

Java EE 7 Application Developer: RESTful Web Services with JAX-RS

Java EE 7 Application Developer · Work through your exam, one topic at a time.

All guide sections

RESTful Web Services with JAX-RS

Domain 6 tests resource classes as HTTP contracts: how paths, methods, media types and parameter annotations combine, and how exceptions turn into status codes.

Resource basics

  • @Path on the class and @GET, @POST, @PUT or @DELETE on methods; @Produces and @Consumes drive content negotiation, producing 406 when no acceptable response type exists and 415 when the request body type is unsupported.
  • Parameter annotations are @PathParam, @QueryParam, @MatrixParam, @HeaderParam, @CookieParam, @FormParam and @BeanParam, with @DefaultValue for optional values.
  • Root resource classes are instantiated per request by default; annotating them @Singleton or using an EJB @Stateless root changes that.
  • A sub-resource locator is a @Path method without an HTTP method annotation that returns an object whose own methods are matched next.

Responses and JAX-RS 2.0

  • Return Response for status control: Response.ok(entity).build(), Response.status(404).build(), Response.noContent().
  • WebApplicationException subclasses map to 4xx and 5xx; an ExceptionMapper registered with @Provider customises the mapping.
  • JAX-RS 2.0 adds the client API (ClientBuilder.newClient(), WebTarget, Invocation.Builder), filters and interceptors with @NameBinding and @PreMatching, asynchronous endpoints via @Suspended AsyncResponse, and bean validation integration.

Worked example

A method annotated @Produces(MediaType.APPLICATION_JSON) returns null after a successful delete. The container answers 204 No Content, not 200 with an empty body, because a null entity with no explicit status becomes No Content. Returning Response.ok().build() instead yields 200, which is the distinction the question is testing.

Traps

  • Omitting @Consumes and receiving 415 for JSON posts.
  • Expecting @PathParam to bind a query-string value; only @QueryParam does that.
  • Caching per-request state in fields of a root resource class that is not a singleton.