Designing REST resource to support multiple methods which produces and consumes exactly the same mime-types

人走茶凉 提交于 2020-01-07 05:35:25

问题


I have 3 methods in ProfileResource:

@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);
}

During server startup below error is thrown, since both getAllProfiles and getProfileByName methods are GET methods, both produce MediaType.APPLICATION_JSON and there is no Path difference b/n them.

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]

How to resolve this issue?


回答1:


You have differentiate Both getAllProfiles() and getProfileByName() by providing difference paths to access them, unless that the server can not distinguish them. so that you will get below error.

A resource model has ambiguous (sub-)resource method for HTTP method GET

provide different paths for both of them, you can do that using @path() annotation.



来源:https://stackoverflow.com/questions/37298844/designing-rest-resource-to-support-multiple-methods-which-produces-and-consumes

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