How to add custom response and abort request in jersey 1.11 filters

Ankur picture Ankur · Jun 17, 2013 · Viewed 12.6k times · Source

I am trying to implement user authentication for rest calls in jersey 1.11 filters.

This is what i have tried

package com.ilrn.session.webservices.rest.filter;

import com.ilrn.entity.User;;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;

public class CustomFilter implements ContainerRequestFilter{

    @Override
    public ContainerRequest filter(ContainerRequest request) {
        User user = Helper.getCurrentUser();
        if(user == null){
            //Need to add custom response and abort request
        }
        return request;
    }

}

Does anyone know any method or something to achieve the same?

Answer

Juned Ahsan picture Juned Ahsan · Jun 17, 2013

In case of error, if you want to send a custom response then you need to throw a WebApplicationException. Create a Response object and send it back using the following exception constructor:

WebApplicationException(Response response) 
          Construct a new instance using the supplied response

Try this:

@Override
public ContainerRequest filter(ContainerRequest request) {
    User user = Helper.getCurrentUser();
    if(user == null){
        ResponseBuilder builder = null;
        String response = "Custom message";
        builder = Response.status(Response.Status.UNAUTHORIZED).entity(response);
        throw new WebApplicationException(builder.build());

    }
    return request;
}