Wednesday, June 21, 2017

JavaEE: JAX-RS - Extracting Values from a URI or Request Header

Extracting Java type of a Request or Response
The javax.ws.rs.core.Context annotation retrieves the Java types related to a request or response and the javax.ws.rs.core.HttpHeaders interface provides information about request headers and cookies.
The RESTful web services need a versioning as the codes are evolving, and putting a version number in the http header is one of ways of doing it.

Extracting Form Data
The @FormParam annotation is used to extract for parameters from HTML forms.

Extracting Path Parameters
The @PathParam annotation lets you use variable UPI path fragments when you call a method.

Extracting Query Parameters
The @QueryParam annotation is used to extract query parameters from the queries of the request URI.  The @DefaultValue annotation defines a default value, which is used if no value is provided for the query parameters.  By default JAX-RS assigns a null value for Object values and zero for primitive data types.

Example Code

@Logging
@Path("/resource")
public class ResourceRestEnd {
   @GET
   public String getHeader(@Context HttpHeaders hh){
      MultivaluedMap<String, String> headerParam = hh.getRequestHeaders();
      return headerParam.getFirst("user-agent");
   }
   
   @GET
   @Path("/name/{lastname}/{firstname}")
   public String getPathParams(@PathParam("lastname") String lastName,
                               @PathParam("firstname") String firstName){
      return "Hello " + firstName + " " + lastName;
   }
   
   @GET
   @Path("/name")
   public String getQueryParams(@DefaultValue("NO_LAST") @QueryParam("lastname") String lastName,
                               @DefaultValue("NO_FIRST") @QueryParam("firstname") String firstName){
      return "Hello " + firstName + " " + lastName;
   }
   
   @POST
   @Consumes(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
   public void post(MultivaluedMap<String, String> formParams){
      List<String> val = formParams.get("some_key");
   }
}

Results

http://localhost:8080/demo/resource

This is the value in the MultivaluedMap when a breakpoint using an IDE is used.
{Accept=[text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8], accept-encoding=[gzip, deflate, sdch, br], accept-language=[en-US,en;q=0.8,ko;q=0.6], cache-control=[max-age=0], connection=[keep-alive], Content-Type=[null], host=[localhost:8080], upgrade-insecure-requests=[1], user-agent=[Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36]}

This is the the header values shown on a web browser.


http://localhost:8080/demo/resource/name/Smith/Tom

http://localhost:8080/demo/resource/name?lastname=Smith&firstname=Tom


No comments:

Post a Comment

Java 9: Flow - Reactive Programming

Programming world has always been changed fast enough and many programming / design paradigms have been introduced such as object oriented p...