9

I've been trying to use:

@RequestMapping(value="/consultaporusuarioperiodo/{idusuario}/{datainicio}/{datafim}", method = RequestMethod.GET)
public String consultaPorPeriodoUsuario(
        @PathVariable("idusuario") Long idUsuario,
        @PathVariable("datainicio") Date dataInicio,
        @PathVariable("datafim") Date dataFim
        ,Model model) {
    Usuario usuario = usuarioService.buscaPorId(idUsuario);
    model.addAttribute("timesheet",timeSheetService.buscaPorPeriodoPorUsuario(dataInicio, dataFim,usuario));
    return "timesheetcrud/consultatimesheet";
}

with this link:

http://localhost:8080/timesheet/consultaporusuarioperiodo/1/21012000/22012000

but I get this error:

HTTP Status 400 -

type Status report

message

description The request sent by the client was syntactically incorrect ().

Apache Tomcat/7.0.27

when I change to:

        @PathVariable("datainicio") String dataInicio,
        @PathVariable("datafim") String dataFim

It's work. What can I do to work with Date ?

thanks

dimitrisli
  • 20,895
  • 12
  • 59
  • 63
user812612
  • 379
  • 4
  • 7
  • 15
  • Try annotating your date parameters with `@DateTimeFormat(pattern = "ddMMyyyy")` – JB Nizet May 30 '13 at 22:27
  • I've already tried with @DateTimeFormat but when I put @PathVariable("datainicio") @DateTimeFormat(pattern = "ddMMyyyy") Date dataInicio, It's not work too :-( Only work with String. – user812612 May 31 '13 at 11:56
  • Tip: Try to use best practices and pass this two date values in Request Body or Query Parameters. http://apigee.com/about/api-best-practices =) – Deividi Cavarzan May 31 '13 at 12:43
  • Mark the answer as correct to help the community :) Also its duplicate of http://stackoverflow.com/questions/15164864/how-to-accept-date-params-in-a-get-request-to-spring-mvc-controller – digz6666 Jun 17 '14 at 11:43

3 Answers3

23

Try:

    @PathVariable("datainicio") @DateTimeFormat(iso=ISO.DATE) String dataInicio,
    @PathVariable("datafim") @DateTimeFormat(iso=ISO.DATE) String dataFim

where ISO.DATE is of yyyy-mm-dd pattern.

dimitrisli
  • 20,895
  • 12
  • 59
  • 63
11

I had to do something very similar. This is what I did:

@PathVariable("datainicio") @DateTimeFormat(pattern = "ddMMyyyy") Date dataInicio

Hope this helps!

Noah Hall-Potvin
  • 187
  • 1
  • 10
0

In Spring's spirit, the best choice should be a convention to impose a unified way of handling Date parameters. And luckily it gives you exactly this little cookie - drop it in application.properties and ... Bob's your uncle:

spring.mvc.date-format=ddMMyyyy

Paul T
  • 396
  • 3
  • 7