mdhtr / java-webapplication

Building a java web application step by step
0 stars 0 forks source link

Add CORS filter #14

Closed mdhtr closed 4 years ago

mdhtr commented 4 years ago

mainly for development purpose

mdhtr commented 4 years ago

I'm not going to put this into the application as a default, because it's not something that should be the default. However, if you need it, here's how to do it:

This solution comes from this stackoverflow post.

Add dependency:

        <dependency>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-servlets</artifactId>
            <version>${jetty.version}</version>
        </dependency>

Configure Jetty:

    private ServletContextHandler createContextHandler() {
        ServletContextHandler contextHandler = new ServletContextHandler();
        contextHandler.setContextPath(CONTEXT_PATH);
        addStaticFileServlet(contextHandler);
        addRestEasyServlet(contextHandler);
        addCorsFilter(contextHandler);
        return contextHandler;
    }

    private void addCorsFilter(ServletContextHandler contextHandler) {
        FilterHolder cors = contextHandler.addFilter(CrossOriginFilter.class,"/*", EnumSet.of(DispatcherType.REQUEST));
        cors.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
        cors.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*");
        cors.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,POST,HEAD");
        cors.setInitParameter(CrossOriginFilter.ALLOWED_HEADERS_PARAM, "X-Requested-With,Content-Type,Accept,Origin");
    }