DOS
DOS

Reputation: 543

Validating Jersey request parameters at Filter stage

I'm looking for an easy way to verify the correct body/query/form/etc parameters are passed into a request. (and also to warn of unknown/unneeded parameters) I know I can inject the context of the request in the actual resource classes and check all the parameters that way but is there anyway of doing this at the filters?

I've looked into the UriInfo and ExtendedUriInfo which will allow me to get the resource class/method but don't show parameters.

Resource class:

    @GET
    @Path("/{img_id}")
    @Produces("application/json")
    public Response getImgWithId(
        @PathParam("img_id") @DefaultValue("0") long imgId,
        @QueryParam("user_id") @DefaultValue("-1") long userId)   

I want to make sure the user passes an img_id path param and the only other param they can pass is user_id. Any other param should receive a warning.

I can do it in this method here by checking the vals/injecting the context but is there a way to do it in an implementation of a ContainerRequestFilter on entry to the application?

Upvotes: 0

Views: 1580

Answers (1)

secondflying
secondflying

Reputation: 871

I think you can subclass com.sun.jersey.spi.container.servlet.ServletContainer.

public class MyServletContainer extends
    com.sun.jersey.spi.container.servlet.ServletContainer {

@Override
public void service(javax.servlet.http.HttpServletRequest request,
        javax.servlet.http.HttpServletResponse response) {
    // do your check
    if (requestCheck()) {
        super.service(request, response);
    } else {
        //write your warning info in response...
    }
}

}

in web.xml:

<servlet>
    <servlet-name>RESTService</servlet-name>
    <servlet-class>com.test.MyServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.chihuo.resource</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>RESTService</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

Upvotes: 1

Related Questions