Menu

Configurable Date format in JAX-RS as @QueryParam

Goal

Control the format of a query param in a JAX-RS endpoint whose type is Date

Description

JAX-RS dictates that parameter unbinding is done in one of two ways:

The parameter bean has a public constructor that accepts a String (this is the case of the java.util.Date class we will be dealing with in this recipe).

The parameter has a static valueOf(String) method.

According to the previous, the way a date query param is parsed in a REST endpoint using JAX-RS is through the deprecated constructor of Date receiving a String parameter, which, I would say, kind “smells”…

I didn’t like that approach nor others I read about in the Internet that would advise a change in the Java implementation to use a String parameter and to parse the date within the corresponding method.

In this recipe, we will implement a solution I would consider very elegant and flexible, with the use of annotations to control the date format.

How to

Declaration of the two annotations, one for a date, discarding the time part, and another for both the date and the time (notice that the annotations may be used in method parameters, and in class fields – this is for the situation we want to use a complete object as @BeanParam in our REST endpoint method).

Next, we implement our ParamConverter that will deal with the conversion of the String we get in our requests into our Date object. Notice that the implementation is prepared to deal with the default situation where the used does not specify any of the previously defined annotations. In that case, our param converter will use a default date format to parse the submitted String into our Date object:

Share this:

Like this:

4 comments

In the implemrntarion there is a potential gap… what is the timezone for the newly parsed Date? Shouldn’t it be received or derived from the request locale or be specified/forced ?
Using Date or DateTime values without timezone is largely the same as saying something costs 200… 200 what? Euro, pounds, dollars, dracmas?