简体   繁体   中英

POSTing with Jersey & JQuery

I'm having an issue POSTing to Jersey using the following...

var details = {username: uname, password: pword};
$.post('login',function(details){
    console.log("sent: "+details);
});

The correct function in my login page is being ran but both username and password are null.

The following is how I consume them...

   public void login(@FormParam("username") String uname,
           @FormParam("password") String pword){
       System.out.println("username = " +  uname + "password = " + pword);
   }

I realise what I POST isn't a form but @FormParam is the only @ I can see that would fit here.

EDIT

Okay, I've got the following right now...

the POST being made

    var details = {'username': username, 'password': password};
$.POST('login', details,function(result){
    console.log(result);
},"json");

The receiving method

@POST
 public Viewable HeyStaksLogin(LoginInfo loginI){
       String uname = loginI.username;
       String pword = loginI.password;
       System.out.println("username = ");
 }

The loginInfo class

@XmlRootElement
public class LoginInfo {
public String username;
public String password;
}

The data is sent as the second argument of the $.post() function (the first being the url and the third being the success callback), like this:

var details = { username: username, password: password };
$.post('login', details, function(result) {
    console.log(result);
});

@FormParam is not usable in this case, as what you are posting is JSON. Here is an example of what you could do:

1) add jersey-json.jar to your project dependencies

2) define the following bean to represent the body of the message:

@XmlRootElement
public class LoginInfo {
    public String username;
    public String password;
}

3) modify the login method as follows:

public void login(LoginInfo li) {
    System.out.println("username = " + li.username + "; password = " + li.password);
}

为您的服务器端方法尝试@Consumes(MediaType.APPLICATION_FORM_URLENCODED)批注

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