简体   繁体   中英

Spring MVC controller with date

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

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.

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

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

Hope this helps!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM