我正在构建一个通用的 Web 服务,需要将所有的查询参数集成到一个字符串中,以便稍后进行解析。我怎么能这么做?
You can access a single param via @QueryParam("name") or all of the params via the context:
@QueryParam("name")
@POST public Response postSomething(@QueryParam("name") String name, @Context UriInfo uriInfo, String content) { MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters(); String nameParam = queryParams.getFirst("name"); }
The key is the @Context jax-rs annotation, which can be used to access:
@Context
UriInfo, Request, HttpHeaders, SecurityContext, Providers
The unparsed query part of the request URI can be obtained from the UriInfo object:
UriInfo
@GET public Representation get(@Context UriInfo uriInfo) { String query = uriInfo.getRequestUri().getQuery(); ... }
Adding a bit more to the accepted answer. It is also possible to get all the query parameters in the following way without adding an additional parameter to the method which maybe useful when maintaining swagger documentation.
@Context private UriInfo uriInfo; @POST public Response postSomething(@QueryParam("name") String name) { MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters(); String nameParam = queryParams.getFirst("name"); }
ref