Twitter

vineri, 9 octombrie 2015

JAX-RS extract the URI path parameters from the request URI

In this post, you can see how to extract the URI path parameters from the request URI in a JAX-RS application

Let's suppose that we have an application named, JaxrsPathParameters_EE7, and the following JAX-RS resource:
import javax.ws.rs.Produces;
import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("/users/{username: [a-zA-Z][a-zA-Z_0-9]*}")
public class HelloUsersResource {

 @GET
 @Path("/admin/{id: \\d+}")
 @Produces("text/plain")
 public String helloAdmin() {
  return "Hello, Admin!";
 }
   
 @GET
 @Path("/user")
 @Produces("text/plain")
 public String helloUser() {
  return "Hello, User!";
 }
}
You already know how to work with this resource from the JAX-RS working with URI path templates example.
Further, let's suppose that you need to extract the URI parameters (in this case, username and id). This is very easy to accomplish via javax.ws.rs.PathParam annotation in the method parameter, as below:
import javax.ws.rs.Produces;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;

@Path("/users/{username: [a-zA-Z][a-zA-Z_0-9]*}")
public class HelloUsersResource {

 @GET
 @Path("/admin/{id: \\d+}")
 @Produces("text/plain")
 public String helloAdmin(@PathParam("username") String admin, @PathParam("id") String id) {
  return "Hello, " + admin + " (" + id + ")!";
 }

 @GET
 @Path("/user")
 @Produces("text/plain")
 public String helloUser(@PathParam("username") String user) {
  return "Hello, " + user + "!";
 }
}
Now, check out two examples:

http://localhost:8080/JaxrsPathParameters_EE7/webresources/users/foo/admin/007
Produces: Hello, foo (007)!

http://localhost:8080/JaxrsPathParameters_EE7/webresources/users/buzz/user
Produces: Hello, buzz!

  • If the URI path template variable cannot be cast to the specified type, the JAX-RS runtime returns an HTTP 400 ("Bad Request") error to the client.
  • If the @PathParam annotation cannot be cast to the specified type, the JAX-RS runtime returns an HTTP 404 ("Not Found") error to the client.

The complete application is available here.

Niciun comentariu:

Trimiteți un comentariu