Spring POST 接收具有空值的对象 [英] Spring POST receives object with null values

查看:28
本文介绍了Spring POST 接收具有空值的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 AngularJS Web 应用程序,看起来它正确地将 JSON 发送到 Tomcat 服务器,但服务器接收空值.这个问题没有帮助,因为我的属性名称已经是小写的,而这个问题没有帮助,因为我已经有了 @RequestBody 符号.正如评论中所指出的,我实际上没有这个符号.我读错了.

I have an AngularJS web application that looks like it is correctly sending JSON to the Tomcat server, but the server receives null values. This question didn't help because my property names are already lowercase, and this question didn't help because I've already got the @RequestBody notation. as pointed out in the comments, I don't actually have this notation. I was reading it wrong.

这是有问题的服务器方法:

Here is the server method in question:

@PostMapping(path="/kind/add")
public @ResponseBody String addNewKind(Kind kind) throws Exception {
    if (kind.getName() == null) {
        throw new Exception("Name not found.");
    }
    kindRepository.save(kind);
    return "Saved";
}

这是它期望接收的 Kind 对象:

Here is the Kind object it expects to receive:

@Entity
public class Kind {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String name;
    @OneToMany(mappedBy="kind")
    private Set<Card> cards;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Set<Card> getCards() {
        return cards;
    }

    public void setCards(Set<Card> cards) {
        this.cards = cards;
    }
}

这是发出请求的方法:

var uri = 'http://localhost:8080/catalog/api/kind/';

function create(name) {
    var deferred = $q.defer();
    var data = {
        'name': name
    };
    $http({
        method: 'POST',
        url: uri + 'add',
        data: angular.toJson(data),
        headers: {
            'Content-Type': 'application/json; charset=UTF-8'
        }
    }).then(function(response) {
        deferred.resolve(response.data);
    }).catch(function(error) {
        console.error('Error while adding kind');
        deferred.reject(error);
    });
    return deferred.promise;
}

这是发送到服务器的 JSON:

This is the JSON sent to the server:

{"name":"Something"}

NB 我假设我可以不发送 idcards 参数而逃脱,因为 id 是自动的-generated 和 cards 可以为空;但是,发送以下 JSON 时我得到相同的空结果:

N.B. I assumed that I can get away without sending id or cards parameters, since id is auto-generated and cards can be empty; however, I get the same null results when sending the following JSON:

{"id":0,"name":"Something","cards":[]}

这些是请求头:

Accept:           application/json, text/plain, */*
Accept-Encoding:  gzip, deflate
Accept-Language:  en-US,en;q=0.5
Connection:       keep-alive
Content-Length:   20
Content-Type:     application/json; charset=UTF-8
Cookie:            __distillery=08c4ef1_752470a4-…ID=lr9remoqoi0ht13v1urq5lq8r7
Host:             localhost:8080
Referer:          http://localhost:8080/catalog/
User-Agent:       Mozilla/5.0 (Windows NT 10.0; …) Gecko/20100101 Firefox/57.0

这是我在调试模式下查看 kind 对象参数时服务器收到的:

And this is what the server receives when I view the kind object argument in debug mode:

kind= Kind
    cards= null
    id= 0
    name= null

推荐答案

您需要使用 @RequestBody 注释在您的方法上.您的控制器不知道主体是什么,因此您发布的对象永远不会绑定(或永远不会制作")到您的方法的 Kind 参数.

You need to use the @RequestBody annotation on your method. Your controller doesn't know what the body is, so your posted object is never bound (or never "makes it") to your method's Kind parameter.

@PostMapping(path="/kind/add")
public String addNewKind(@RequestBody Kind kind) throws Exception {
    if (kind.getName() == null) {
        throw new Exception("Name not found.");
    }
    kindRepository.save(kind);
    return "Saved";
}

如果您希望返回新的Kind",您希望控制器方法如下所示:

If you are expecting the new 'Kind' to be returned, you'd want your controller method to look like this:

@PostMapping(path="/kind/add")
public Kind addNewKind(@RequestBody Kind kind) throws Exception {
    if (kind.getName() == null) {
        throw new Exception("Name not found.");
    }
    return kindRepository.save(kind);
}

顺便说一句,我注意到您在写出 JSON 时在 JSON 中使用了单引号.由于您正在使用 angular.toJson() 转换数据,因此您应该没问题.如果您尝试通过直接发送 JSON 字符串进行交互,这通常不起作用.JSON 不使用单引号.

On a side note, I notice you are using single quotes in your JSON when you write it out. Since you are converting data with angular.toJson(), you should be OK there. If you are trying to interact by sending a JSON string directly, this will generally not work. JSON doesn't use single quotes.

这篇关于Spring POST 接收具有空值的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆