Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ContainerResponseFilter not working

In wildfly 8.1 with REST services, I wanted to implement CORS ContainerRequestFilter and ContainerResponseFilter.

My request filter is working properly but ContainerResponseFilter never gets loaded nor called

package org.test.rest;

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.ext.Provider;

@Provider 
@PreMatching // <-- EDIT : This was my mistake ! DO NOT ADD THIS
public class CorsResponseFilter implements ContainerResponseFilter {
    public CorsResponseFilter() {
        System.out.println("CorsResponseFilter.init");
    }

    @Override
    public void filter(ContainerRequestContext req,
            ContainerResponseContext resp) throws IOException {
        System.out.println("CorsResponseFilter.filter");
        resp.getHeaders().add("Access-Control-Allow-Origin", "*");
        resp.getHeaders().add("Access-Control-Allow-Credentials", "true");
        resp.getHeaders().add("Access-Control-Allow-Methods",
                "GET, POST, DELETE, PUT");
        resp.getHeaders().add("Access-Control-Allow-Headers",
                "Content-Type, Accept");
    }

}

This seems to me as a Wildfly / resteasy bug. Do you have another idea / am I missing something ?

like image 582
Cerber Avatar asked Aug 31 '14 10:08

Cerber


1 Answers

You are mixing ContainerRequestFilter and ContainerResponseFilter in your question. As you want to send additional Headers to the client the ContainerResponseFilter is the right one.

The @PreMatching annotation can be applied to a ContainerRequestFilter "to indicate that such filter should be applied globally on all resources in the application before the actual resource matching occurs".

Adding it to a ContainerResponseFilter does not make sense. Just remove the annotation and your filter should work.

like image 188
lefloh Avatar answered Oct 17 '22 09:10

lefloh