设计REST资源以支持生成和使用完全相同的mime类型的多个方法

时间:2016-05-18 11:53:52

标签: jersey jersey-2.0

我在ProfileResource中有3个方法:

@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Profile> getAllProfiles() {
    return profileService.getAllProfiles();
}

@GET
@Path("{profileId}")
@Produces(MediaType.APPLICATION_JSON)
public Profile getProfile(@PathParam("profileId") String profileId) {
    return profileService.getProfile(profileId);
}

@GET
@Produces(MediaType.APPLICATION_JSON)
public Profile getProfileByName(@QueryParam("profileName") String profileName) {
    return profileService.getProfileByName(profileName);
}

在服务器启动期间,抛出错误,因为getAllProfilesgetProfileByName方法都是GET方法,两者都生成MediaType.APPLICATION_JSON并且没有Path个区别b / n他们。

org.glassfish.jersey.server.model.ModelValidationException: Validation of the application resource model has failed during application initialization.
[[FATAL] A resource model has ambiguous (sub-)resource method for HTTP method GET and input mime-types as defined by"@Consumes" and "@Produces" annotations at Java methods public restapi.model.Profile restapi.resources.ProfileResource.getProfileByName(java.lang.String) and public java.util.List restapi.resources.ProfileResource.getAllProfiles() at matching regular expression /profiles. These two methods produces and consumes exactly the same mime-types and therefore their invocation as a resource methods will always fail.; source='org.glassfish.jersey.server.model.RuntimeResource@4e1d247f']
    at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:555) ~[jersey-server-2.22.2.jar:na]

如何解决此问题?

1 个答案:

答案 0 :(得分:1)

您可以通过提供访问它们的差异路径来区分getAllProfiles()和getProfileByName(),除非服务器无法区分它们。这样你就会得到以下错误。

  

资源模型具有HTTP方法GET的模糊(子)资源方法

为它们提供不同的路径,你可以使用@path()注释来实现。