.= 'tag.htm'; break; case 'flag': $pre .= $default_pre .= 'flag.htm'; break; case 'my': $pre .= $default_pre .= 'my.htm'; break; case 'my_password': $pre .= $default_pre .= 'my_password.htm'; break; case 'my_bind': $pre .= $default_pre .= 'my_bind.htm'; break; case 'my_avatar': $pre .= $default_pre .= 'my_avatar.htm'; break; case 'home_article': $pre .= $default_pre .= 'home_article.htm'; break; case 'home_comment': $pre .= $default_pre .= 'home_comment.htm'; break; case 'user': $pre .= $default_pre .= 'user.htm'; break; case 'user_login': $pre .= $default_pre .= 'user_login.htm'; break; case 'user_create': $pre .= $default_pre .= 'user_create.htm'; break; case 'user_resetpw': $pre .= $default_pre .= 'user_resetpw.htm'; break; case 'user_resetpw_complete': $pre .= $default_pre .= 'user_resetpw_complete.htm'; break; case 'user_comment': $pre .= $default_pre .= 'user_comment.htm'; break; case 'single_page': $pre .= $default_pre .= 'single_page.htm'; break; case 'search': $pre .= $default_pre .= 'search.htm'; break; case 'operate_sticky': $pre .= $default_pre .= 'operate_sticky.htm'; break; case 'operate_close': $pre .= $default_pre .= 'operate_close.htm'; break; case 'operate_delete': $pre .= $default_pre .= 'operate_delete.htm'; break; case 'operate_move': $pre .= $default_pre .= 'operate_move.htm'; break; case '404': $pre .= $default_pre .= '404.htm'; break; case 'read_404': $pre .= $default_pre .= 'read_404.htm'; break; case 'list_404': $pre .= $default_pre .= 'list_404.htm'; break; default: $pre .= $default_pre .= theme_mode_pre(); break; } if ($config['theme']) { $conffile = APP_PATH . 'view/template/' . $config['theme'] . '/conf.json'; $json = is_file($conffile) ? xn_json_decode(file_get_contents($conffile)) : array(); } !empty($json['installed']) and $path_file = APP_PATH . 'view/template/' . $config['theme'] . '/htm/' . ($id ? $id . '_' : '') . $pre; (empty($path_file) || !is_file($path_file)) and $path_file = APP_PATH . 'view/template/' . $config['theme'] . '/htm/' . $pre; if (!empty($config['theme_child']) && is_array($config['theme_child'])) { foreach ($config['theme_child'] as $theme) { if (empty($theme) || is_array($theme)) continue; $path_file = APP_PATH . 'view/template/' . $theme . '/htm/' . ($id ? $id . '_' : '') . $pre; !is_file($path_file) and $path_file = APP_PATH . 'view/template/' . $theme . '/htm/' . $pre; } } !is_file($path_file) and $path_file = APP_PATH . ($dir ? 'plugin/' . $dir . '/view/htm/' : 'view/htm/') . $default_pre; return $path_file; } function theme_mode_pre($type = 0) { global $config; $mode = $config['setting']['website_mode']; $pre = ''; if (1 == $mode) { $pre .= 2 == $type ? 'portal_category.htm' : 'portal.htm'; } elseif (2 == $mode) { $pre .= 2 == $type ? 'flat_category.htm' : 'flat.htm'; } else { $pre .= 2 == $type ? 'index_category.htm' : 'index.htm'; } return $pre; } ?>javascript - Spring POST receives object with null values - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Spring POST receives object with null values - Stack Overflow

programmeradmin0浏览0评论

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. Edit: as pointed out in the ments, 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";
}

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;
    }
}

Here is the method that makes the request:

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;
}

This is the JSON sent to the server:

{"name":"Something"}

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":[]}

These are the request headers:

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

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

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. Edit: as pointed out in the ments, 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";
}

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;
    }
}

Here is the method that makes the request:

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;
}

This is the JSON sent to the server:

{"name":"Something"}

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":[]}

These are the request headers:

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

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
Share Improve this question edited Dec 4, 2017 at 10:01 catholicposer asked Dec 3, 2017 at 12:54 catholicposercatholicposer 771 silver badge7 bronze badges 2
  • "..., because I've already got the @RequestBody notation" - Where? I only see the @ResponseBody. – helospark Commented Dec 3, 2017 at 15:18
  • @helospark You're right, how embarrassing! I was looking at @RequestBody and reading @ResponseBody. – catholicposer Commented Dec 4, 2017 at 9:59
Add a ment  | 

1 Answer 1

Reset to default 6

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";
}

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);
}

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.

发布评论

评论列表(0)

  1. 暂无评论