JAX-RS : How to Get Values from @MatrixParam in Jersey

Connect with

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

You can choose version of jersey as per your choice.


   com.sun.jersey
   jersey-server
   1.9

2. Get Value from @MatrixParam

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 parameter 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"
}

2. Download Source Code

You can download source code of JAX-RS: jersey by click here.

3.References

  1. Jersey Official site
  2. JAX-RS official site
  3. Oracle Java Web services tutorial
  4. Wikipedia

Connect with

Leave a Reply

Your email address will not be published. Required fields are marked *