[RESOLVIDO] Erro(CORS) ao executar chamada no webservice com Jetty

Boa noite, estou tentando realizar uma chamada a um webservice más está retornando o erro abaixo;

Requisição cross-origin bloqueada: A política de mesma origem (Same Origin Policy) impede a leitura do recurso remoto em http://localhost:8484/testeImpressao/impressao/. (Motivo: o cabeçalho CORS ‘Access-Control-Allow-Origin’ não está presente).

Segue o código que estou utilizando.

Servidor WebService

@Path("testeWS")
public class ApplicationCommandResource {
      
        
    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/teste")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response impressao( @QueryParam("nome") String stringJson) {        
               
        JSONObject jsonObject = new JSONObject();
        
        Integer tam = 0;
        jsonObject.put(tam.toString(), "teste 1");        
        tam += 1;
        jsonObject.put(tam.toString(), "teste 2");
        tam += 1;
        jsonObject.put(tam.toString(), "teste 3");   
        
        return Response
            .status(200)
            .header("Access-Control-Allow-Origin", "*")
            .header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
            .header("Access-Control-Allow-Credentials", "true")
            .header("Access-Control-Allow-Methods", "POST")            
            .entity(jsonObject.toString())
            .build();         
                  
    }`

CLiente WebService

$.ajax({
                    type: "POST",
                    url: "http://localhost:8484/testeWS/teste/" ,
                    data: "{'0':'1','1':'teste','2':'1','3':'asw'}",				       	
                    dataType: "json",  
                    headers: { 'Content-Type': 'application/json' ,
                        'X-Requested-With': 'XMLHttpRequest', 
                        'Access-Control-Allow-Origin': '*' ,
                        'Access-Control-Allow-Headers':'origin, content-type, accept, authorization'
                    },  	
                    success: function(data){  				         
                        alert("saida:" + data[3]); 	
                    },beforeSend: function(){				       		
                        $("body").addClass("loading"); 
                    },
                    complete: function(){					    	
                        $("body").removeClass("loading");
                    },
                    error: function (xhr, status, error) {
                        
                     
                    }
                });

Edita seu código do Client WebService e posta o erro do console.

Eu tive este problema a um tempo, tive que criar um filtro:

@Component
public class CORSFilter extends OncePerRequestFilter {
    private static final Log LOG = LogFactory.getLog(CORSFilter.class);

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        response.addHeader("Access-Control-Allow-Origin", "*");
        if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
            LOG.trace("Sending Header....");
            // CORS "pre-flight" request
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            response.addHeader("Access-Control-Allow-Headers", "Content-Type");
            response.addHeader("Access-Control-Max-Age", "1");
        }
        filterChain.doFilter(request, response);
    }
}

Espero que ajude.

2 curtidas

Desculpe, a demora em responder, o filtro resolveu o problema.
E no cliente, não precisou colocar todas as informações no header.
Valeu, cido18!