简体   繁体   中英

Post Json Object from AngularJs to java JAX-RS service

I google this matter for hours but I still cannot find solution.

Here is my java code

  @POST
  public String doLogin(User user) {
    System.out.println(" = " + user.getUsername());
    return "";
  }

and

 @XmlRootElement
  @XmlAccessorType(XmlAccessType.FIELD)
  public class User {
    String username;

    String password;

    public String getUsername() {
      return username;
    }

    public void setUsername(String username) {
      this.username = username;
    }

    public String getPassword() {
      return password;
    }

    public void setPassword(String password) {
      this.password = password;
    }
  }

and here is my AngularJs code

 angular.module('notesApp', []).controller('MainCtrl', ['$http', function($http) {
      var self = this;
      self.submit = function() {
        $http({
            method: 'POST',
            url: 'http://127.0.0.1:8080/Test/app/login',
            headers : {'Content-Type': 'application/json'},
            data: self.user //forms user object
          })
          .then(function(response) {
            console.log(response.data);
            return response.data;
          }, function(response) {

          });
      }
  }]);

My error message was: SEVERE: A message body reader for Java class entity.User, and Java type class entity.User, and MIME media type application/json; charset=UTF-8 was not found, as I could not access 'user' Object in java code.

Could you please figure out which part I do wrong? Thank you so much.

You need to read from POST body and not Query Params .

You can use this:

  @POST
  public String doLogin( User user) {
    System.out.println(" = " + user.getUsername());
    return "";
  }

@QueryParam is used to the queryparams which you'll pass as ?user=xyz@gmail.com

Remove query param You will get a serialized string. deSerialize it to User.

@POST
public String doLogin(User user) {
    System.out.println(" = " + user.getUsername());
    return "";
}

You are setting the data field on your POST . This sets the HTTP Body , not an HTTP query param.

Check the browser debugger networking panel to ensure that you are sending what you expect to the server. will open it and then 'send' your user and look at what is sent. Does this object look exactly like what User in java expects?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM