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
Swing on Osx: How to Trap Command-Q
Run a Single Test Method with Maven
Tokenizing a String But Ignoring Delimiters Within Quotes
How to Access Resources in Jar File
In Java, When Should I Create a Checked Exception, and When Should It Be a Runtime Exception
Debug a Java Application Without Starting the Jvm with Debug Arguments
Create a Maven Project in Eclipse Complains "Could Not Resolve Archetype"
Find Elements Inside Forms and Iframe Using Java and Selenium Webdriver
Jdk9: an Illegal Reflective Access Operation Has Occurred. Org.Python.Core.Pysystemstate
Spring Boot 2.0.X Disable Security for Certain Profile
Jax-Rs - How to Return JSON and Http Status Code Together
@Aspectj Pointcut for All Methods of a Class with Specific Annotation
Windows Shortcut (.Lnk) Parser in Java
No-Throw Virtualmachineerror Guarantees
How to Find Where Jdk Is Installed on My Windows MAChine