0

The last couple of days, I have been struggling with an issue. I've created a rest service hosted by a Grizzly server inside an OSGi container. Everything is working perfectly at this point.

Now, I want to add a header in every response.Not so complex or illogical right? Yet, I can't find a way to do it.

I have tried to:

1) Get the response object inside the rest functions as this question suggests (pretty textbook when you are not under OSGi).

2) Add a handler using the code above (in this case the service method is never called)

    server.getServerConfiguration().addHttpHandler(
            new HttpHandler() {
                @Override
                public void service(Request arg0, Response arg1)
                        throws Exception {
                    arg1.setHeader("Access-Control-Allow-Origin", "*");
                }
            });

I am using jersey-server/client/core 1.18.1 and grizzly2-server 1.18.1, hence i prefer a solution that can be applied in this version, but I am willing to update jar versions if it cannot be done in 1.18.x.

Community
  • 1
  • 1
Mario
  • 767
  • 1
  • 14
  • 42

1 Answers1

2

You could give a try to Jersey filters.
In a nutshell, you should create class implementing ContainerResponseFilter:

public class MyFilter implements ContainerResponseFilter {

    @Override
    public void filter(
        ContainerRequest request,
        ContainerResponse response
    ) throws IOException {
        request.getHttpHeaders().add(<header name>, <header value>);
    }
}

Then, you should register this filter in your Jersey server configuration.
Please, note, that this filter would be invoked on every response. To bind it only to specific resources, you could use annotation-binding, that is described here.
All other information you could find here.

mkrakhin
  • 3,386
  • 1
  • 21
  • 34
  • 2
    OP is using Jersey 1, You are using the Jersey/JAX-RS 2 inferface. The arguments to `filter` in Jersey 1 are `ContainerRequest` and `ContainerResponse` :-) – Paul Samsotha Mar 06 '15 at 08:43
  • Sure, I haven't noticed :) Thank you :) – mkrakhin Mar 06 '15 at 08:55
  • Thanks for the answer. I can't try it now, so i will check it a little bit later. Hope it fits in my code :) – Mario Mar 06 '15 at 08:58
  • 2
    @Mario See the bottom of [this answer](http://stackoverflow.com/a/28067653/2587435) if you need help registering the filter – Paul Samsotha Mar 06 '15 at 09:02
  • Thanks both of you guys. This is working perfectly, i can't express how gradefull i am. – Mario Mar 06 '15 at 10:36