通过AJAX发送JSON到RESTful服务(球衣)返回空值
问题描述:
抱歉再次提问,但我找不到解决方案,我的问题 - 无论是在这里,还是其他地方。我有一个使用jersey的RESTful服务器,它应该通过来自客户端的ajax来使用JSON ....但它返回一个空值。为什么??通过AJAX发送JSON到RESTful服务(球衣)返回空值
REST:
@POST
@Path("/addPoint")
@Consumes({ MediaType.APPLICATION_JSON })
@Produces({ MediaType.APPLICATION_JSON })
public WayPoint addPoint(@QueryParam("coordinate")String coordinate, @QueryParam("RouteId")Long RouteId) {
WayPoint waypoint = new WayPoint();
waypoint.setCoordinate(coordinate);
waypoint.setRouteId(RouteId);
System.out.println(waypoint);
return getEntityManager().merge(waypoint);
}
对象:
@Entity
@XmlRootElement
public class WayPoint {
@Id
@Column(nullable = false)
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
private String coordinate;
private Long RouteId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCoordinate() {
return coordinate;
}
public void setCoordinate(String coordinate) {
this.coordinate = coordinate;
}
public Long getRouteId() {
return RouteId;
}
public void setRouteId(Long routeId) {
this.RouteId = routeId;
}
}
和AJAX调用:
this.AddPoint = function(coords, routeid){
var test = JSON.stringify({ coordinate: coords, RouteId: routeid });
console.log(test);
$.ajax({
url: thePath,
type: "POST",
data: JSON.stringify({ coordinate: coords, RouteId: routeid }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(response) {
alert("new point added!");
console.log(response);
},
error:function(res){
alert("Cannot save point! " + res.statusText);
}
});
};
我不明白这一点...协调和路由ID是“空“当我尝试以这种方式提取它们时(通过@queryParam)
答
据我所知,您只能使用@QueryParam
进行GET请求。
对于POST,您可以将要填充的对象作为方法参数,Jersey将自动为您实例化它。
我想你只是要确保实例化的对象具有适当的getters和setter。
一个GET例如:
@GET
@Path("logout")
@Produces(MediaType.APPLICATION_JSON)
public Response logout(@NotNull @QueryParam("user_id") int userId,
@NotNull @QueryParam("token") String token) {
一个POST例如:
@POST
@Path("register")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response register(RegisterUserParams registerUserParams) {
当我改变Ajax调用和annotaion到GET
,参数仍然为空 - 我怎样才能获得通过参数POST?我想我真的很愚蠢atm ...... – messerbill 2015-01-15 17:16:01
你不应该为你的ajax调用的'data'参数做'JSON.stringify'。只需将其保留为JSON对象即可。 – 2015-01-15 17:53:26
多数民众赞成它,谢谢你兄弟! – messerbill 2015-01-15 22:58:33