apss1943
apss1943

Reputation: 269

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.

Upvotes: 0

Views: 680

Answers (4)

KenF
KenF

Reputation: 624

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?

Upvotes: 0

Sandeep Kaul
Sandeep Kaul

Reputation: 3267

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 [email protected]

Upvotes: 1

David Lavender
David Lavender

Reputation: 8311

@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.

Upvotes: 0

Karthik Tsaliki
Karthik Tsaliki

Reputation: 196

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

Upvotes: 0

Related Questions