JAX-RS @Path annotation with regular expression match example
This page gives you an example using JAX-RS @Path annotation, how to bind a URI pattern to your java method using regular
expression match.
In the previous examples we have given details of application setup, dependencies, web.xml file configurations: If you want to
know about these configuration, please refer these:
Restful web services using RESTEasy hello world example.
Restful web services using Jersey hello world example.
Look at the below class to apply @Path annotation with regular expression to your method:
package com.java2novice.restful;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
@Path("/employee")
public class EmployeeService {
@GET
@Path("{empId: [0-9]+}")
public Response getEmployeeById(@PathParam("empId") String empId){
return Response.status(200).entity("Got employee with id : " + empId).build();
}
@GET
@Path("/name/{empName: [a-zA-Z\\s]+}")
public Response getEmployeeByName(@PathParam("empName") String name){
return Response.status(200).entity("Got employee with name : " + name).build();
}
}
|
In the above example, if you use "/employee/123" URI pattern, getEmployeeById() method will be invoked, and you will get "Got employee with id : 123"
as a response.
If you use "/employee/name/javanovice" URI pattern, then getEmployeeByName() method will be invoked and you will get "Got employee with name : javanovice"
as a response.
In the next page you will see an example on how to use @PathParam annotation.
|