Aug 14, 2015

How to extract a @MatrixParam in a PathSegment of the URI ( http://localhsot:8080/names;age=10/maxi )

During reading of the book RESTful Java with JAX-RS 2.0 I found the matrix parameters in the middle of a URI.

http://localhost:8080/HelloWorld/resources/greeting/name;age=10/maxi;old=20

When using this on Glassfish 4.1 with Jersey as JAX RS Implementation, the simple resource method with
a @MatrixParam doesn't find the parameter.

@GET@Path( "names/{after}")@Produces(MediaType.TEXT_PLAIN)public String getMatrix(         @PathParam("after") String after,        @MatrixParam("age") @DefaultValue( "-1") String age,        @MatrixParam("old") int old        ) {    System.out.println("Matrix Param age " + age);    System.out.println("Matrix Param old " + old);    System.out.println("PathParam after : " + after );


With the call above, age is not found and a -1 is issued on the output. 
The age matrix parameter is only found, when it is on the last path segment. To get the matrix parameter on a segment inside of the path, you can use a PathSegment

@GET@Path( "{namePath: names}/{after}")@Produces(MediaType.TEXT_PLAIN)public String getMatrix(         @PathParam( "namePath") PathSegment namePath,        @PathParam("after") String after,        @MatrixParam("age")@DefaultValue( "-1") String age,        @MatrixParam("old") int old        ) {    MultivaluedMap<String, String> matrixParameters = namePath.getMatrixParameters();    System.out.println("matrixParameters = " + matrixParameters);    System.out.println("Matrix Param age " + age);    System.out.println("Matrix Param old " + old);    System.out.println("PathParam after : " + after );

The part for the "name" is a named path element as regular expression, but with the fixed text "name". 
In the parameter list of the JAX-RS Method, this segment is used as PathSegment, which allows to 
extract the matrix parameters. Here is the output: 

Information:   Grizzly Framework 2.3.15 started in: 32ms - bound to [/0.0.0.0:8181]Information:   matrixParameters = {age=[10]}Information:   Matrix Param age -1Information:   Matrix Param old 20Information:   PathParam after : maxi

For the PathSegment, I found the hint here

On Glassfish with Jersey this works, have to test it also with RestEASY