CXF JAXRS - How do I pass Date as QueryParam

后端 未结 4 1181
忘掉有多难
忘掉有多难 2020-12-05 17:21

I have a service defined as follows.

public String getData(@QueryParam(\"date\") Date date)

I\'m trying to pass a java.util.Date to

4条回答
  •  忘掉有多难
    2020-12-05 17:34

    Percepiton's answer was very useful, but ParameterHandler has been deprecated in Apache-cxf 3.0, see the Apache-cxf 3.0 Migration Guide:

    CXF JAX-RS ParameterHandler has been dropped, please use JAX-RS 2.0 ParamConverterProvider.

    So I add an example with the ParamConverterProvider :

    public class DateParameterConverterProvider implements ParamConverterProvider {
    
        @Override
        public  ParamConverter getConverter(Class type, Type type1, Annotation[] antns) {
            if (Date.class.equals(type)) {
                @SuppressWarnings("unchecked")
                ParamConverter paramConverter = (ParamConverter) new DateParameterConverter();
                return paramConverter;
            }
            return null;
        }
    
    }
    
    public class DateParameterConverter implements ParamConverter {
    
        public static final String format = "yyyy-MM-dd"; // set the format to whatever you need
    
        @Override
        public Date fromString(String string) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
            try {
                return simpleDateFormat.parse(string);
            } catch (ParseException ex) {
                throw new WebApplicationException(ex);
            }
        }
    
        @Override
        public String toString(Date t) {
            return new SimpleDateFormat(format).format(t);
        }
    
    }
    

    The @SuppressWarnings is required to suppress an "unchecked or unsafe operations" warning during compilation. See How do I address unchecked cast warnings for more details.

    The ParamConverterProvider can be registred as provider. Here is how I did it:

      
          
               ...
          
    
          
              
          
      
    
      
    

    See Apache-cxf JAX-RS : Services Configuration for more information.

提交回复
热议问题