Configure Response object for Rest Services inside a Jersey-Grizzly server, in OSGi container (CORS error prevention with Jersey 1x)

假如想象 提交于 2020-03-05 11:48:50

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/28894430/configure-response-object-for-rest-services-inside-a-jersey-grizzly-server-in-o

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!