我在将参数“日期”传递给我的 java api 时遇到错误, Controller 的代码如下:
@RequestMapping(value = "/horario/{fecha}", method = RequestMethod.GET)
@ResponseBody
public Object queryHorariosLibres(@PathVariable("fecha") Date fecha) {
List<Long> horariosLibres = null;
List<Long> turnosTomados = turnoService.getTurnosTomados(fecha);
Calendar dia = new GregorianCalendar();
dia.setTime(fecha);
Horario horario = horarioRepository.findByDia(dia.get(Calendar.DAY_OF_WEEK));
horariosLibres = horario.getHorariosLibres(turnosTomados);
if (horariosLibres == null) {
return "hola";
} else
return horariosLibres;
}
这是我收到的错误:
There was an unexpected error (type=Bad Request, status=400).
Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type @org.springframework.web.bind.annotation.PathVariable java.util.Date for value '2016-02-15'; nested exception is java.lang.IllegalArgumentException
这是我的模型的代码: 这是管理时间的“horario”类:
@Entity
@Table(name = "horario")
public class Horario implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private Integer dia;
private Long horarioInicio;
private Long horarioFin;
Getters And Setter's
@Transient
public List<Long> getHorarios(){
List<Long> horarios = new ArrayList<Long>();
for(Long i = horarioInicio; i <= horarioFin; i+=300){
horarios.add(i);
}
return horarios;
}
@Transient
public List<Long> getHorariosLibres(List<Long> horariosTomados){
List<Long> horariosLibres = getHorarios();
horariosLibres.removeAll(horariosTomados);
return horariosLibres;
}
...
这是管理约会的“轮次/时间表”类:
@Entity
@Table(name = "turno")
public class Turno implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String solicitante;
private String telefono;
private TipoDocumento tipoDocumento;
private String numeroDocumento;
private String email;
private Integer horario;
private String numeroTurno;
private Date fecha;
private String controlFecha;
Getters and Setters
}
最佳答案
您需要将 @DateTimeFormat 注释添加到您的参数中。
@DateTimeFormat(pattern="yyyy-MM-dd")
@RequestMapping(value = "/horario/{fecha}", method = RequestMethod.GET)
@ResponseBody
public Object queryHorariosLibres(@PathVariable("fecha") @DateTimeFormat(pattern="yyyy-MM-dd") Date fecha) {
List<Long> horariosLibres = null;
List<Long> turnosTomados = turnoService.getTurnosTomados(fecha);
Calendar dia = new GregorianCalendar();
dia.setTime(fecha);
Horario horario = horarioRepository.findByDia(dia.get(Calendar.DAY_OF_WEEK));
horariosLibres = horario.getHorariosLibres(turnosTomados);
if (horariosLibres == null) {
return "hola";
} else
return horariosLibres;
}
关于java - Java API 日期错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35461217/