JAX-RS方法不返回来自对象

时间:2015-11-11 21:02:49

标签: json angularjs jax-rs

您好我有简单的Angular和JAX RS应用程序。我的班级:

public class User {

    private String firstName;
    private String lastName;

    public User(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

}

文件AngularCtrl.js是Angular控制器:

    (function () {
    var app = angular.module('app', []);
    var serviceURI = "/Airlines/rest/";
    app.controller('flightCtrl', ['$scope', '$http', function ($scope, $http) {
            $scope.value;
            getAllUsers($scope, $http);
        }]);
    function getAllUsers($scope, $http) {
        $http.get(serviceURI + "flights").success(function (data) {
            $scope.value = data;
        }).error(function (error) {
            alert("Some Error Occurred!");
        });
    }

})();

休息班:

@RequestScoped
@Path("/flights")
public class FlightRest {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public User listAll() {
        User user = new User("John", "Thompson");
        System.out.println("Before return");
        return user;
    }

}

和简单的观点:

<html>
<head>
    <title>Arilines</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/main.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</head>
<body>
    <div data-ng-app="app">
        <div  data-ng-controller="flightCtrl">
            {{value.firstName}} {{value.lastName}}
        </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
    <script src="js/AngularCtrl.js"></script>
</body>

当我开始申请时,我会收到提醒:

  

警告(&#34;发生了一些错误!&#34;);

我班上有什么不对,而不是成功错误?为什么不获取JSON数据?我确定我的请求到达了JAX-RS类,因为在控制台中我看到来自类的消息

  

System.out.println(&#34;返回之前&#34;);

1 个答案:

答案 0 :(得分:0)

您的JAX-RS类没有问题。它按预期返回一个json。我执行了代码,它在浏览器上正确显示了用户名。

我必须做的唯一调整是从JAX-RS向我的响应添加标头以允许跨域访问(CORS),因为我在另一个端口上托管了REST服务。 这是我做的调整: -

@GET
@Produces(MediaType.APPLICATION_JSON)
public Response listAll() {
    User user = new User("John", "Thompson");
    System.out.println("Before return");
    return Response.status(Status.OK)
    .header("Access-Control-Allow-Origin", "*")
    .header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
    .entity(user)
    .type(MediaType.APPLICATION_JSON).build();
}