Set Access-Control-Allow-Origin in Jetty

2019-09-11 06:16发布

问题:

I need to set "Access-Control-Allow-Origin" to "*" by code.

Reading this i've tried to set org.eclipse.jetty.servlets.CrossOriginFilter using setInitParameter:

        Server  server = new Server(activity.WEB_SERVER_PORT);  
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);

        context.setWelcomeFiles(new String[] { "index.html" });
        context.setContextPath("/");

        context.setInitParameter("org.eclipse.jetty.servlets.CrossOriginFilter", "/*");

        TheServlet sv = new TheServlet();
        context.addServlet(new ServletHolder(sv),"/servleturl");

        server.setHandler(context); 
        try {
            server.start();
        } catch (Exception e) { }

But it doesn't work. How can I solve?

回答1:

Try using the addFilter method with a filterHolder. This snippet might help

    FilterHolder filterHolder = new FilterHolder(CrossOriginFilter.class);
    filterHolder.setInitParameter("allowedOrigins", "*");
    filterHolder.setInitParameter("allowedMethods", "GET, POST");

    ServletContextHandler servletContextHandler;
    servletContextHandler = new ServletContextHandler(webServer, "/", ServletContextHandler.SESSIONS);
    servletContextHandler.addServlet(atmosphereServletHolder, "/atmosphere/*");
    servletContextHandler.addServlet(jerseyServletHolder, "/jersey/*");
    servletContextHandler.addFilter(filterHolder, "/*", null);