如何使用http POST JAX-RS将对象从AngularJS服务传递到Java

时间:2015-03-22 11:22:12

标签: java angularjs rest jax-rs angularjs-service

所以我正在建立一个电子邮件客户端,为Google API提供授权的RESTful调用(OAuth 2和JAX-RS)。

我已成功导入电子邮件和联系人。我现在想发一封电子邮件。

我有一个控制器,可以调用服务(成功)

app.controller('ComposeController', function($scope, $cookies, ComposeService) {

    //Some test data
    var email = $cookies.email;
    $scope.to = "********@yahoo.com";
    $scope.subject = "test";
    $scope.body = "test";

    $scope.compose = function() {

        //Create an email object
        $scope.newEmail = {
                'to' : $scope.to,
                'from' : email,
                'subject' : $scope.subject,
                'body' : $scope.body
        };

        //Parse to JSON
        var emailJSON = angular.toJson($scope.newEmail);

        //Make call to ComposeService
        var response = ComposeService.compose(emailJSON).success(function(jsonData) {

            response = jsonData;
            alert(response);
        });
    }
});

然后,服务调用Java类

app.factory('ComposeService', function($http) {

    var response = {};

    response.compose = function(newEmail) {

        return $http({

            method: 'POST',
            url: 'resources/composeMail/send',
            data: {
                newEmail : newEmail
            },
            headers: {'Content-Type':'application/json'}
        });
    }

    return response;
});

这是被称为

的类
@Path("/composeMail")
public class Compose {

    @POST
    @Path("/send")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String sendMessage(NewEmail newEmail) throws MessagingException,
            IOException {

        System.out.println("I am here");
    .....

这是NewEmail对象

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class NewEmail {

    private String to;
    private String from;
    private String subject;
    private String body; 

    public NewEmail(String to, String from, String subject, String body) {
        this.to = to;
        this.from = from;
        this.subject = subject;
        this.body = body;
    }
......

不会调用Java类。我收到400响应(错误请求)。如果我删除' NewEmail newEmail'从构造函数中调用类,我看到了预期的输出。

感谢。

1 个答案:

答案 0 :(得分:0)

乍一看JS代码看起来不错。你需要在JAX-RS方面做一些工作。这是因为JAX-RS不知道如何将请求中的JSON转换为NewEmail类。

你有两个选择:

  1. 为您的Provider课程撰写自定义NewEmail。请参阅示例this link
  2. 更改方法参数以接受JSON并在方法中将其转换。从长远来看,这可能不太理想。