若是想在客戶端傳遞"yyyy-MM-dd"等類型的Date數據,如UserResource.java:java
package soc.resource; import java.util.Date; import java.util.List; import java.util.Map; import javax.inject.Singleton; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.springframework.beans.factory.annotation.Autowired; import soc.entity.User; import soc.service.UserService; @Singleton @Path("user") public class UserResource { @Autowired private UserService userService; @GET @Path("birthday") @Produces(MediaType.APPLICATION_JSON) public List<User> queryByBirthday(@QueryParam("date") Date date){ return userService.queryByBirthday(date); } }
若想成功實現,能夠自定義一個String和Date轉換的工具類,繼承ParamConverterProviderspring
package soc.config; import java.lang.annotation.Annotation; import java.lang.reflect.Type; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import javax.ws.rs.WebApplicationException; import javax.ws.rs.ext.ParamConverter; import javax.ws.rs.ext.ParamConverterProvider; import javax.ws.rs.ext.Provider; public class DateConverterProvider implements ParamConverterProvider{ 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); } } @Override public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) { if (Date.class.equals(rawType)) { return (ParamConverter<T>) new DateParameterConverter(); } return null; } }
而後在本身的繼承ResourceConfig的配置類裏註冊一下,如:json
package soc.config; //import org.codehaus.jackson.jaxrs.JacksonJsonProvider; import org.glassfish.jersey.filter.LoggingFilter; //import org.glassfish.jersey.jackson.JacksonFeature; import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.spring.scope.RequestContextFilter; import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider; public class ApplicationApi extends ResourceConfig { public ApplicationApi() { // 註冊數據轉換器 register(JacksonJsonProvider.class); // 註冊日誌 register(LoggingFilter.class); packages("soc.resource"); // register filters register(RequestContextFilter.class); // register mine exception class ,to find the trace of exception register(DebugMapperException.class); // register my DateConverterProvider register(DateConverterProvider.class); } }
這時在Client端傳遞queryParam("date")時傳遞yyyy-MM-dd格式的便可自動解析。app