How do you map multiple query parameters to the fields of a bean on Jersey GET request?

后端 未结 5 1642
傲寒
傲寒 2020-11-30 19:27

A service class has a @GET operation that accepts multiple parameters. These parameters are passed in as query parameters to the @GET service call.

5条回答
  •  暖寄归人
    2020-11-30 20:20

    You can create a custom Provider.

    @Provider
    @Component
    public class RequestParameterBeanProvider implements MessageBodyReader
    {
        // save the uri
        @Context
        private UriInfo uriInfo;
    
        // the list of bean classes that need to be marshalled from
        // request parameters
        private List paramBeanClassList;
    
        // list of enum fields of the parameter beans
        private Map enumFieldMap = new HashMap();
    
        @Override
        public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType)
        {
            return paramBeanClassList.contains(type);
        }
    
        @Override
        public Object readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap httpHeaders, InputStream entityStream) throws IOException, WebApplicationException
        {
            MultivaluedMap params = uriInfo.getQueryParameters();
    
            Object newRequestParamBean;
            try
            {
                // Create the parameter bean
                newRequestParamBean = type.newInstance();
    
                // Populate the parameter bean properties
                for (Entry> param : params.entrySet())
                {
                    String key = param.getKey();
                    Object value = param.getValue().iterator().next();
    
                    // set the property
                    BeanUtils.setProperty(newRequestParamBean, key, value);
                }
            }
            catch (Exception e)
            {
                throw new WebApplicationException(e, 500);
            }
    
            return newRequestParamBean;
        }
    
        public void setParamBeanClassList(List paramBeanClassList)
        {
            this.paramBeanClassList = paramBeanClassList;
    
        }
    

提交回复
热议问题