有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

web服务java JAXR中的rest多个参数

我正在编写RESTful web服务。我所有的方法,比如添加、删除、获取工作。但我想创建一个方法,显示用户借了什么书

public class UserManagement {

private Map<Long, UserMaker> userMaker = DataBase.getUserMaker();

public UserManagement(){           //id , name, surname, nin, status of book
userMaker.put((long) 1, new UserMaker(1,"John", "Castles", 12345,0)); 

public UserMaker hireBook(UserMaker user, BookMaker book){         // method who update status hiring book  , if 0 that means book is rented
    if(user.getId() <= 0){
        return null;
    }
    book.setStatus((int) user.getId());                //
    user.setWhatIhave((int) (book.getId()));          // convert int to long
    userMaker.put(user.getId(), user);
    return user;
}  }

现在我想用多个参数的方法

@Path("/user")
public class UserCRUD {

UserManagement userManagementWS = new UserManagement();

@PUT
@Path("/{idU}/{idB}")             
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public UserMaker hireBook(
                          @PathParam("idU") long idU, UserMaker user,
                          @PathParam("idB") long idB, BookMaker book) {
    user.setId(idU);
    return userManagementWS.hireBook(user, book);             //borrowing books
} }

我犯了个错误,但一切看起来都很好:

Method public project.emil.lib.model.UserMaker project.emil.lib.resources.UserCRUD.hireBook(long,project.emil.lib.model.UserMaker,long,project.emil.lib.model.BookMaker) on resource class project.emil.lib.resources.UserCRUD contains multiple parameters with no annotation. Unable to resolve the injection source.

有什么建议吗?:)


共 (1) 个答案

  1. # 1 楼答案

    资源方法不能有多个实体参数。您可以有多个@PathParam@QueryParam等,但每个资源方法中只有一个未注释的参数

    3.3.2.1 Entity Parameters The value of a parameter not annotated with @FormParam or any of the annotations listed in in Section 3.2, called the entity parameter, is mapped from the request entity body. Conversion between an entity body and a Java type is the responsibility of an entity provider, see Section 4.2. Resource methods MUST have at most one entity parameter.

    http://download.oracle.com/otn-pub/jcp/jaxrs-2_1-final-eval-spec/jaxrs-2_1-final-spec.pdf

    您可以从资源方法中删除UserMaker user,而是将用户id传递给userManagementWS.hireBook(idU, book)。然后通过userMaker.get(idU)Map<Long, UserMaker>检索用户。 https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#get-java.lang.Object-

    但我建议你重新构造你的api。我发现这个链接非常有用