How to add general HEADER attributes to the response of my web service java?

0

I am exposing an api rest with Javaee, but I have the problem of CORS because I am consuming it from an Angular app, I know that in each method of the service to each response I can place a header, but I do not want to add a header to each response , I want something like an Interceptor that adds a header to each Response in order to avoid the CORS problem.

I'm not using any framework, I'm working with netbeans, and my project does not use a web.xml file, I've already searched for solutions based on that file on the internet and they have not worked for me. I'm using JPA, from the entities create the service, netbeans allows that option.

    
asked by Ricardo Gabriel 24.05.2018 в 18:28
source

1 answer

0

If you are using Java EE to expose a RESTful API, it means that you are using JAX-RS - > Jersey, RestEasy or one of its implementations .

JAX-RS allows you to create generalizations for these cases. Mind you, you should be using version 2.0 at least

That interceptor of the speaker is called in this case ContainerResponseFilter . Let's see an example:

1. we created the filter CORS

package su.estructura.de.paquetes;

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.core.MultivaluedMap;

public class CORSResponseFilter implements ContainerResponseFilter {

    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {


        MultivaluedMap<String, Object> headers = responseContext.getHeaders();

        headers.add("Access-Control-Allow-Origin", "*");        
        headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");          
        headers.add("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Codingpedia");               

    }
}

2.

We must register the new filter in the app, this depends on the configuration you have.

A. If you use JAX-RS together with javax.ws.rs.core.Application:

It's as simple as adding @Provider to your filter, the rest is done by the framework ..

@Provider
public class CORSResponseFilter implements ContainerResponseFilter {}

B. ** If you have used Jersey as the implementation to JAX-RS ** and you have overwritten any of the methods of ResourceConfig or Application to register your clases,singletons,etc. There will be register it manually:

package su.estructura.de.paquetes;

import org.glassfish.jersey.server.ResourceConfig;

public class RESTBootstrap extends ResourceConfig   {

    public RESTBootstrap(){

        register(CORSResponseFilter.class);
        packages("paquetes.que.se", "van.a.escanear");
    }
}

It's pretty simple, I hope it's helpful.

    
answered by 07.08.2018 в 01:29