Jetty server configuration

旧时模样 提交于 2019-12-01 10:34:58

You are mixing Jersey 1.x with Jersey 2.x, which should not be done. Your filter class is based on Jersey 1.x. Your ResourceConfig is Jersey 2.x. I know this because Jersey 1.x ResourceConfig doesn't have the register() method. With Jersey 1.x, this is howwe would register your above filter

resourceConfig.getContainerResponseFilters().add(new CORSFilter());

And that would be enough. But Jersey 2.x does not have this way of adding filters. We need to register everything.

That being said, if you are using Jersey 2.x, I highly suggest getting rid of all your Jersey 1.x dependencies. After doing so, the first thing you will notice is that your filter class will no longer compile. Here's how the refactored 2.x filter should look like:

import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;

@Provider
public class CORSFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext request,
            ContainerResponseContext response) throws IOException {
        response.getHeaders().add("Access-Control-Allow-Origin", "*");
        response.getHeaders().add("Access-Control-Allow-Headers",
                "origin, content-type, accept, authorization");
        response.getHeaders().add("Access-Control-Allow-Credentials", "true");
        response.getHeaders().add("Access-Control-Allow-Methods",
                "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    }
}

Using the above filter should work.

Similar approach as peeskillet mentioned, but I have held jetty configuration in jetty.xml in my application.

So to add custom filters I had to register them in the jetty.xml file as:

<New class="org.eclipse.jetty.servlet.ServletHolder">
<Arg>
    <New class="com.sun.jersey.spi.container.servlet.ServletContainer">
        <Arg>
            <New class="com.sun.jersey.api.core.PackagesResourceConfig">
                <Arg>
                    <Map>
                      <Entry>
                        <Item>com.sun.jersey.config.property.packages</Item>
                        <Item>...my package</Item>
                      </Entry>
                      <Entry>
                        <Item>com.sun.jersey.spi.container.ContainerResponseFilters</Item>
                        <Item>...MyCorsResponseFilter</Item>
                      </Entry>
                    </Map>
                </Arg>
            </New>
        </Arg>
    </New>
</Arg>

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