Jersey (JAX-RS) matrix URI parameters handling guide

URL with matrix URI looks like:

http://www.example.com/map;lat=50;long=20;scale=32000

;lat=50;long=20;scale=32000 represents matrix parameters. Please refer W3C article on it.

Using @MatrixParam annotation we can get matrix parameters value from API URI in Jersey Resources classes.

This is a part of Jersey (JAX-RS) Restful Web Services Development Guides series. Please read Jersey + Spring Boot getting started guide.

Using @MatrixParam at instance variable and method parameters

File : MatrixUriResource.java

package in.geekmj.resource;

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.Produces;
import javax.ws.rs.core.MediaType;

@Path("/matrix-uri")
@Produces(MediaType.APPLICATION_JSON)
public class MatrixUriResource {

	/*
	 * We can inject matrix URI parameter as an instance variables
	 * using @MatrixParam
	 */

	@MatrixParam("lat")
	private Integer latitude;

	@MatrixParam("long")
	private Integer longitude;

	/* We can inject matrix URI parameter method using @MatrixParam */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@GET
	public Map getRequestCookie(@MatrixParam("scale") Integer scale, @MatrixParam("type") String type) {

		Map matrixParams = new HashMap();
		matrixParams.put("latitude", latitude);
		matrixParams.put("longitude", longitude);
		matrixParams.put("scale", scale);
		matrixParams.put("type", type);
		return matrixParams;
	}
}

Testing http://localhost:8080/matrix-uri;lat=50;long=20;scale=32000;type=geo with Postman chrome plugin.

api URI with matrix parameters handling in jersey

API URI with matrix parameters handling in jersey

Response:

{
  "latitude": 50,
  "scale": 32000,
  "type": "geo",
  "longitude": 20
}

References

  1. To know more about Matrix URIs, click here.
  2. Official Jersey Documentation
Download Icon SmallDownload the Full ProjectGithub IconFollow Project On Github

Leave a Reply

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