问题描述
我正在使用Jersey来构建RESTful服务,并且我有一些Servlet在多个方法中使用相同的PathParam。 所以我想将PathParam值存储在全局变量中,而不是在每个方法中存储局部变量。
就像是:
@Path("mensas/{mensaID}/dishes/{dishID}")
public class CommentServlet {
//Global PathParams
@PathParam("mensaID")
long mensaID;
@PathParam("dishID")
long dishID;
@GET
@Path("comments")
public String getDishComments() {
// ...
}
}
代替:
@Path("mensas/{mensaID}/dishes/{dishID}")
public class CommentServlet {
@GET
@Path("comments")
//Local PathParams
public String getDishComments(@PathParam("mensaID") long mensaID, @PathParam("dishID") long dishID) {
// ...
}
}
也许还有其他更好的方法?
1楼
您可以通过将所有参数提取到一个新类(保留原始@PathParam注释)来重构代码:
public class DishParams {
@PathParam("mensaID")
private long mensaID;
@PathParam("dishID")
private long dishID;
public long getMensaID() {
return mensaID;
}
public void setMensaID(long mensaID) {
this.mensaID = mensaID;
}
public long getDishID() {
return dishID;
}
public void setDishID(long dishID) {
this.dishID = dishID;
}
}
然后使用上述@BeanParam注释的类声明一个参数
public class CommentServlet {
@GET
@Path("comments")
public String getDishComments(@BeanParam DishParams params) {
// ...
return null;
}
}
希望能帮助到你!