Java JAX-RS custom parameter with default value

自古美人都是妖i 提交于 2019-12-10 17:41:03

问题


Let's say I have this (this is just a sample):

@GET
@Path(value="address")
@Produces("application/json")
public Response getAddress(@QueryParam("user") User user){
  ...
}

and User is

class User{
...
 public static User valueOf(String user){
   if(user == null) return DEFAULT_USER;
   return dao.findById(user);
 }    
}

If I do /api/address?user=amir everything works but the idea is if I don't provide a value for user then I want DEFAULT_USER to be used. But this doesn't actually call valueOf. Is there a way to fix this?


回答1:


JAX-RS has the @DefaultValue annotation:

@QueryParam("user") @DefaultValue("__DEFAULT")



class User{
...
 public static User valueOf(String user){
   if(user == null||"__DEFAULT".equals(user) return DEFAULT_USER;
   return dao.findById(user);
 }    
}


来源:https://stackoverflow.com/questions/5641778/java-jax-rs-custom-parameter-with-default-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!