java jersey 参数,Java Jersey-在相同的@path上具有不同参数的相同方法?

I'm newbie on creating web services with Jersey and I'm facing with this problem:

@GET

@Path("/logoutUser")

@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")

public Response logoutUser(@QueryParam("userName") String userName) {

if (userName.equalsIgnoreCase("jmart") || userName.equalsIgnoreCase("jromero")) {

return Response.status(Response.Status.OK).entity("Logout realizado").type(MediaType.APPLICATION_JSON).build();

}else {

throw new CustomNotFoundException("No se ha podido realizar el logout del usuario " + userName);

}

}

@GET

@Path("/logoutUser")

@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")

public Response logoutUser(@QueryParam("idUsuario") int idUsuario) {

if (idUsuario == 1 || idUsuario == 2) {

return Response.status(Response.Status.OK).entity("Logout realizado").type(MediaType.APPLICATION_JSON).build();

}else {

throw new CustomNotFoundException("No se ha podido realizar el logout del usuario " + idUsuario);

}

}

Obviously when I'm trying to call any of the two methods my server throws an exception.

Is there any solution of implementing the same method with different parameter on the same path?

解决方案

I don't think you can do what you are trying to do with Jersey. Even if you were to switch to an @PathParam it isn't going to give you the control that you are looking for. If I were you though, I wouldn't try to do the conditional logic in Jersey anyway, it is honestly a bit confusing. Instead I would get all the @QueryParams in a list and then look to see if what you want is in that list. See the example here. The other option is to just get both @QueryParams and see which one is null. Since @QueryParams are optional you should check for null anyway. Your new code might look like:

@GET

@Path("/logoutUser")

@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")

public Response logoutUser(@QueryParam("idUsuario") int idUsuario, @QueryParam("userName") String userName) {

if(userName != null) {

//do what you want with the username

}

else if (idUsuario == 1 || idUsuario == 2) {

//do what you want with the id

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值