Custom date format with jax-rs in apache cxf?

I was looking for search queries to figure out how to set the date format when I use jax-rs on apache CXF. I looked at the codes and it seems that it only supports primitives, an enumeration, and a special hack, assuming that the type associated with @FormParam has a constructor with one string parameter. This forces me to use String instead of Date if I want to use FormParam. it's disgusting. Is there a better way to do this?

@POST @Path("/xxx") public String addPackage(@FormParam("startDate") Date startDate) { ... } 

thanks

+4
source share
4 answers

starting with CXF 2.3.2, the ParameterHandler will do this. You can also always override the date value (passed as part of the request, etc.) Using the default RequestHandler filters Date (String) to work

+4
source

One simple apporach takes a parameter as a String and parses it in the body of the method to convert it to java.util.Date

Another is to create one class for which the constructor takes a parameter of type String. Do the same as I said in the first approach.

here is the code for the second approach.

 @Path("date-test") public class DateTest{ @GET @Path("/print-date") public void printDate(@FormParam("date") DateAdapter adapter){ System.out.println(adapter.getDate()); } public static class DateAdapter{ private Date date; public DateAdapter(String date){ try { this.date = new SimpleDateFormat("dd/MM/yyyy").parse(date); } catch (Exception e) { } } public Date getDate(){ return this.date; } } } 

Hope this helps.

+4
source

After reading the CXF codes (2.2.5), this is not possible, and it is hard-coded to use the Date (String) constructor, therefore, regardless of the date (String).

0
source

In Apache-cxf 3.0, you can use ParamConverterProvider to convert a parameter to Date .

The following code is copied from my answer to this question .

 public class DateParameterConverterProvider implements ParamConverterProvider { @Override public <T> ParamConverter<T> getConverter(Class<T> type, Type type1, Annotation[] antns) { if (Date.class.equals(type)) { return (ParamConverter<T>) new DateParameterConverter(); } return null; } } public class DateParameterConverter implements ParamConverter<Date> { 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); } } 
0
source

Source: https://habr.com/ru/post/1309829/


All Articles