从服务器接收JSON数据时没有’Access-Control-Allow-Origin’标头

我试图让客户端从服务器接收JSON数据,但是,它不断弹出错误方法。 当我尝试使用Chrome进行调试时,会弹出: XMLHttpRequest cannot load http://localhost:8080/TransportationNetwork/rest/paths?st=3,6. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. XMLHttpRequest cannot load http://localhost:8080/TransportationNetwork/rest/paths?st=3,6. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

我试图将dataType更改为’jsonp’,但它不起作用。 但是,当我使用POSTMAN测试来自Server的数据时,一切正常,我可以看到JSON数据来自服务器。

这张 照片显示了POSTMAN的测试结果 图片显示了来自服务器的POSTMAN测试结果

以下是我在服务器端和客户端的代码:有谁能告诉我如何为我的java代码添加’Access-Control-Allow-Origin’标头?(如果是这个问题)

Java代码:

 @Path("/paths") public class PathsResource { PathDao pathDao; public PathsResource() { pathDao = new PathDao(); } @GET @Produces(MediaType.APPLICATION_JSON) //@Consumes("text/plain") public List pathsInfo(@QueryParam("st") String st) { System.out.println("Searching paths : " + st); return pathDao.getEdgeList(st); } } 

Javascript:

 var serviceURL = "http://localhost:8080/TransportationNetwork/rest/paths"; $('#findPaths').click(function() { getPaths(); }); function getPaths() { console.log('display paths'); $.ajax({ type:'GET', url: serviceURL, dataType:'json', // data type get back from server data:'st=' + dataToServer(), //data sent to server success: renderList, error: function(jqXHR, textStatus, errorThrown){ alert('Path Finder: ' + textStatus); } }); } function dataToServer() { var array = ""; str1 = $('#source').val(); str2 = $('#target').val(); array = str1 + "," + str2; return array; } function renderList(data) { //var parsedData = JSON.parse(data); var list = data == null ? [] : (data instanceof Array ? data : [data]); $('#PathList li').remove(); $.each(list, function(index, path) { $('#PathList').append('
  • '+ path.source + ' -> ' + path.target + ': ' + path.weight + '
  • '); }); }