Explain @Path annotation in Rest Web services with example

The @Path annotation identifies the URI path template to which the resource responds, and this annotation is specified at the class level of a resource. The @Path annotation's value is a partial URI path template relative to the base URI of the server on which the resource is deployed, the context root of the WAR, and the URL pattern to which the server helper servlet responds.

Now let us see this annotation with an example

@Path("/employees/{employeename}")
public class EmployeeResource {

    @GET
    @Produces("text/xml")
    public String getEmployee(@PathParam("employeename") String employeeName) {
        ...
    }
}

If it is required that a employee name must only consist of lower and upper case numeric characters, it is possible to declare a particular regular expression that will override the default regular expression, "[^/]+?". The following example shows how this could be used with the @Path annotation.

@Path("/employees/{employeename: [a-zA-Z][a-zA-Z_0-9]}")

 

The following table lists some examples of URI path template variables and how the URIs are resolved after substitution. The following variable names and values are used in the examples:

  • name1:john

  • name2mckenzie

  • name3: jadoo

  • locationPeople%20Street

  • questionwhy

  • ans: gotcha!

 

Examples of URI path templates

 

 URI Path Template 

 URI After Substitution 

 http://example.com/{name1}/{name2}/

 http://example.com/john/mckenzie/

 http://example.com/{question}/{question}/{ans}/

 http://example.com/why/why/gotcha/

 http://example.com/maps/{location}

 http://example.com/maps/People%20Street

 http://example.com/{name3}/home/

 http://example.com/jadoo/home/

 

 

J2EE 12

FOLLOW US ON LinkedIn



Explore Tutu'rself