我正在尝试以json格式将User对象发送到我的REST api。
var user={
firstName: "someVal",lastName: "", email: "", contactPhone: "", password: ""
};
var url="http://localhost:8085/MyappName/appliPath/login";
$.ajax({
method:'POST',
contentType: "application/json",
datatype:'json',
url : url,
data:JSON.stringify(user),
success: function(data){
console.log(data);
},
error: function(error){
console.log(error);
}
});
});
以下是我的登录控制器类代码
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public static User register(User user){
System.out.println("in register");
User register = null;
if(!validateUser(user.getEmail())){
System.out.println("calling new user");
register = loginDao.addNewUser(user);
System.out.println("returning user");
}
return register;
}
如何将复杂的用户发送到我的代码?我应该说@Path("{user}")
吗?
答案 0 :(得分:0)
HI您可以使用Post方法将复杂对象发送到Rest API。 下面是将接受User JOSN对象的REST API。 您可以在此处详细了解如何发布复杂对象:http://entityclass.in/rest/jerseyClientGetXml.htm
import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@Path("/StudentService")
public class StudentService {
@POST
@Path("/update")
@Consumes(MediaType.APPLICATION_JSON)
public Response consumeJOSN( User user ) {
User output = user.toString();
return Response.status(200).entity(output).build();
}
}
对于这个RestFull API,我编写了JAVA客户端
public class ClientJerseyPost {
public static void main(String[] args) {
try {
User user = new User();
user.setName("JON");
user.setAddress("Paris");
user.setId(5);
String resturl = "http://localhost:8080/RestJerseyClientXML/rest/StudentService/update";
Client client = Client.create();
WebResource webResource = client.resource(resturl);
ClientResponse response = webResource.accept("application/json")
.post(ClientResponse.class, student);
String output = response.getEntity(String.class);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
} catch (Exception e) {
}
}
}