Question

When using regex for @Path fragments, Jersey runtime results in returning 404 for the resources that do not match the regex pattern. Is there a way to customize this behaviour and return 400 (BAD_REQUEST) or add a meaningful message to the response?

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

If the resource is invoked with users/1243 it results in 404. I would like to add a response message about the valid username patterns. I could move the validation inside the Restful method and validate. But this is tedious. I have dozens of the methods and I would need to call the validation from all these methods.

EDIT: Am using Jersey 1.17 and not can not use Jersey 2.0 due to application impact.

Was it helpful?

Solution

You can use a ContainerRequestFilter to catch requests before they hit the API, and use injected UriInfo to determine if there's a users path element. If there is, check the username's validity.

I would note, however, that I don't think 400 is a reasonable response. There's nothing wrong with the syntax of the request.

OTHER TIPS

To add to the @Eric Stein's response, having regex in @Path will result in 404 without execution reaching filter methods. So validation has to be pushed inside the filter method. In order to abort the call and return the customized response from filter used below code.



    //groovy code
    class MyCustomFilter implements ContainerRequestFilter
    {
      @Override
        public ContainerRequest filter(ContainerRequest request) {
    //do the validation for the resource URI and abort flow for errors
    throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).entity("Not valid input").build())
    ...
    .. 
     //for success scenarios, return the request with optional customization

            return request;
        }
    }
    @ResourceFilters(MyCustomFilter)
    @Path('/users/{userId}/scripts')
    class MyJaxRsResource {

    }


Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top