JAX-RS matrix parameters example demonstrates how you retrieve parameter value from the request using @MatrixParm annotation in Jersey rest API. In JAX-RS, getting values from MatrixParam in jersey is very easy. @MatrixParam annotation is used to bind the key=value from path variable parameters in Jersey which is separated by semi-colon (i.e 😉 and it’s very handy.
1. Maven dependency for JAX-RS Matrix parameters
In this JAX-RS tutorial, you can choose version of jersey as per your choice for retrieving value from matrix parameters using @MatrixParam annotation.
com.sun.jersey jersey-server 1.9
2. Get Value from @MatrixParam annotation
In this JAX-RS tutorial series of JAX-RS matrix parameters you can retriev values from matraix parameter using @MatrixParam annotation.
package com.mysoftkey.jaxrs;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.GET;
import javax.ws.rs.MatrixParam;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* This Jersey implementation of service class is used to demonstrate to get values from @MatrixParam.
*
* @author Ranjeet Jha
*
*/
@Path("matrixParam")
public class MatrixParamService {
/**
* This method is used to pull parameters from MatrixParam.
*
* Service URL : http://localhost:8080/jersey/matrixParam/ranjeet;from=ranjeet.kr;to=anila.jha;subject=subject line;body=mail body
*
* @param user
* @param from
* @param to
* @param body
* @param subject
* @return
*/
@GET
@Path("{user}")
@Produces(MediaType.APPLICATION_JSON)
public Response getMailInfo(@PathParam("user") String user, @MatrixParam("from") String from,
@MatrixParam("to") String to, @MatrixParam("body") String body, @MatrixParam("subject") String subject) {
Map map = new HashMap ();
map.put("userName", user);
map.put("sender", from);
map.put("recipeint", to);
map.put("mailBody", body);
map.put("subject", subject);
return Response.status(200).entity(map).build();
}
}
Service URL : http://localhost:8080/jersey/matrixParam/ranjeet;from=ranjeet.kr;to=anila.jha;subject=subject line;body=mail body
output:
{
sender: "ranjeet.kr@gmail.com",
recipeint: "anila.jha@gmail.com",
mailBody: "mail body",
subject: "subject line",
userName: "ranjeet"
}