質問

I am pretty new to dropwizard and guice. When I hit my api from an ajax code locally, I get the following error on my browser's console. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

After researching the error many people are suggesting adding CrossORiginFilter to my dropwizard code. which is done thru env.addFilter But I am trying to use Guice. here is my main class

public static void main( String[] args ) throws Exception
{
    new TListService().run( args );
}

@Override
public void initialize( Bootstrap<TListServiceConfiguration> bootstrap )
{
    bootstrap.setName( "tlist" );
    bootstrap.addBundle( GuiceBundle.< TListServiceConfiguration > newBuilder().addModule( new JpaPersistModule( this.getClass().getPackage().getName() ) ).setConfigClass( TListServiceConfiguration.class )
            .enableAutoConfig( this.getClass().getPackage().getName() ).build() );
}

@Override
public void run( TListServiceConfiguration config, Environment env ) throws Exception
{        
}

and here is my ajax code:

$(document).ready(function() {
    $('#btnSend').click(function(){
        var apiUrl = $('#txtServer').val() + $("#selectApi").val();
        console.log("URL: " + apiUrl);
        var postData = JSON.parse($('#textData').val());
        console.log(postData);
        console.log(JSON.stringify(postData));
        $.ajax({
            url: apiUrl,
            async: false,
            type: 'POST',
            dataType:"json",
            contentType:"application/json; charset=UTF-8",
            data: JSON.stringify(postData),
        })
        .done(function(data) {
            console.log("success");
            console.log(data);
        })
        .fail(function() {
            console.error("Error");
        })
        .always(function() {
            console.log("complete");
        });
    });     
});
役に立ちましたか?

解決 2

We had the same problem, wanted to use guice to inject the filters, the solution that was arrived modify the GuiceBudle to accpet filters injection, in our case were still wearing the @WebFilter to do this, otherwise you will have to use the Environment.

In AutoConfig class you can create a addFilters method, which will use the library to look for reflections of all classes annotated with @WebFilter, would be something like this:

public void addFilters(Environment env, Injector injector) {
    Set<Class<?>> annotatedClasses = reflections.getTypesAnnotatedWith(WebFilter.class);
    for (Class<?> annotated : annotatedClasses) {
        env.addFilter(injector.getInstance(annotated), annotated.getAnnotation(WebFilter.class).urlPatterns()[0];
    }
}

or you can later add the filter in the run method:

@Override
public void run( TListServiceConfiguration config, Environment env ) throws Exception {      
    env.addFilter(Filter.class, "urlPatterns");
}

他のヒント

First, create a filter to allow cross domain requests

public class CrossDomainFilter implements Filter {
       public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

            HttpServletResponse res = (HttpServletResponse) response;

            res.setHeader("Access-Control-Allow-Origin", "*");
            res.setHeader("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
            res.setHeader("Access-Control-Allow-Credentials", "true");
            res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
            res.setHeader("Access-Control-Max-Age", "1209600");

            chain.doFilter(request, response);
        }
}

Then, add mapping in run() method of your Service class

env.getApplicationContext().addFilter(CrossDomainFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST, DispatcherType.ERROR));

Hope this helps.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top