How to Accept Date Params in a Get Request to Spring MVC Controller

How to accept Date params in a GET request to Spring MVC Controller?

Ok, I solved it.
Writing it for anyone who might be tired after a full day of non-stop coding & miss such a silly thing.

@RequestMapping(value="/fetch" , method=RequestMethod.GET)
public @ResponseBody String fetchResult(@RequestParam("from") @DateTimeFormat(pattern="yyyy-MM-dd") Date fromDate) {
//Content goes here
}

Yes, it's simple. Just add the DateTimeFormat annotation.

Passing date to request param in Spring MVC

Use @DateTimeFormat("MMddyyyy")

public @ResponseBody List<RecordDisplay> getRecords(
@RequestParam(value="userID") Long userID,
@RequestParam(value="fromDate") @DateTimeFormat(pattern="MMddyyyy") Date fromDate,
@RequestParam(value="toDate") @DateTimeFormat(pattern="MMddyyyy") Date toDate) {

Spring @RequestParam Date Formatting

Use the Spring annotation DateTimeFormat

@RequestMapping(params="/updateDate")
public @ResponseBody String updateDate(HttpServletRequest request
, @RequestParam Integer productId
, @RequestParam @DateTimeFormat(pattern="MM/dd/yyyy") Date dateReceived) {
// Code here...
}

How to pass Timestamp,date in request param in spring boot using Postman

You can use this format for your input

    2020-04-01T09:18:18Z -> @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") 

or use iso dateTime input like below

2020-04-01T09:18:18.000+00:00 -> @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)

below code work with your input

@GetMapping("/getevents8")
public List<EventCalendar> getEvents8(@RequestParam int page,
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") Date d1,
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") Date d2) {
Sort sort = new Sort(Sort.Direction.DESC, "createRecord");
Pageable pageRequest = PageRequest.of(page, 3, sort);
List<EventCalendar> events;

events = eventRepository.findByCreateRecordBetween(d1, d2, pageRequest);

return events;
}

Spring GET method how to raise Exception if an unknown request param in controller

Query param are often optional, so it's rare that a server could reject you because of that.

But what you are trying to achieve can be implemented with an Interceptor, you need some reflection to get the parameters of your method and verify that each client param is defined on the signature of your method.

Something like:

@Component
public class QueryParamInterceptor implements HandlerInterceptor {

@Override
public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) {
Map<String, String[]> clientRequestParameters = request.getParameterMap();
MethodParameter[] methodParameters = ((HandlerMethod) handler).getMethodParameters();
List<String> definedMethodsParameters = Arrays.stream(methodParameters)
.flatMap(methodParameter -> Arrays.stream(methodParameter.getParameterAnnotations()))
.filter(annotation -> annotation.annotationType().isAssignableFrom(RequestParam.class))
.map(annotation -> ((RequestParam) annotation).name())
.collect(Collectors.toList());

for (String clientRequestParameterKey : clientRequestParameters.keySet()) {
if (!definedMethodsParameters.contains(clientRequestParameterKey)) {
throw new IllegalArgumentException("The parameter " + clientRequestParameterKey + " passed by the client is unknown");
}
}
return true;
}
}

Note that an interceptor will be called at each request. So I would not use that in production due to the high cost of object introspection..



Related Topics



Leave a reply



Submit