Как использовать LocalDateTime - PullRequest
0 голосов
/ 19 июня 2020

как правильно решить ошибку LocalDateTime?

Я новичок в Spring, поэтому я попытался найти способ решить эту проблему в Интернете, но я не могу его обойти.

Это моя сущность

package com.reserve.entities;

import java.time.LocalDateTime;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;

@Entity
public class Flight extends AbstractEntity {


    private String flightNumber;
    private String operatingAirlines;
    private String departureCity;
    private String arrivalCity;


    @DateTimeFormat(iso=ISO.DATE)
    private Date dateOfDeparture;


    @Column(name="estimatedDepartureTime",columnDefinition="TIMESTAMP")      
    private LocalDateTime estimatedDepartureTime;

    public String getFlightNumber() {
        return flightNumber;
    }
    public void setFlightNumber(String flightNumber) {
        this.flightNumber = flightNumber;
    }
    public String getOperatingAirlines() {
        return operatingAirlines;
    }
    public void setOperatingAirlines(String operatingAirlines) {
        this.operatingAirlines = operatingAirlines;
    }
    public String getDepartureCity() {
        return departureCity;
    }
    public void setDepartureCity(String departureCity) {
        this.departureCity = departureCity;
    }
    public String getArrivalCity() {
        return arrivalCity;
    }
    public void setArrivalCity(String arrivalCity) {
        this.arrivalCity = arrivalCity;
    }
    public Date getDateOfDeparture() {
        return dateOfDeparture;
    }
    public void setDateOfDeparture(Date dateOfDeparture) {
        this.dateOfDeparture = dateOfDeparture;
    }

    public LocalDateTime getEstimatedDepartureTime() {
        return estimatedDepartureTime;
    }
    public void setEstimatedDepartureTime(LocalDateTime estimatedDepartureTime) {
        this.estimatedDepartureTime = estimatedDepartureTime;
    }
    @Override
    public String toString() {
        return "Flight [flightNumber=" + flightNumber + ", operatingAirlines=" + operatingAirlines + ", departureCity="
                + departureCity + ", arrivalCity=" + arrivalCity + ", dateOfDeparture=" + dateOfDeparture
                + ", estimatedDepartureTime=" + estimatedDepartureTime + "]";
    }   

}

Это мой контролер.

Я не уверен, какая информация требуется.

Пожалуйста, дайте мне знать, если есть дополнительная информация, которая могла бы Помощь.


package com.reserve.controllers;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.reserve.entities.Flight;
import com.reserve.repository.FlightRepository;

@Controller
public class FlightController {

    @Autowired
    private FlightRepository flightRepository;

    @RequestMapping("findFlights")
    public String findFlights(
            @RequestParam("from")String from, 
            @RequestParam("to")String to, 
            @RequestParam("departureDate")
            @DateTimeFormat(pattern = "MM-dd-yyyy")
            Date departureDate,
            Model model) 
    {
        List<Flight> flights = flightRepository.findFlights(from,to,departureDate);

        model.addAttribute("flights", flights);
        return "displayFlights";
    }

    @RequestMapping("/ourFlights")
    public String ourFlights() {
        return "ourFlights";
    }

    @RequestMapping(value="/add", method=RequestMethod.POST)
    public String addFlights(@ModelAttribute("flight")Flight flight,Model model) {
        Flight save = flightRepository.save(flight);
        String msg = save.getFlightNumber() + " from " + save.getDepartureCity() + " to "
                + save.getArrivalCity() + " has been added.";
        model.addAttribute("msg", msg);
        return "ourFlights";
    }
}

Это мой JSP файл


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
     <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@page isELIgnored="false"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Money Wise</title>
<link rel="stylesheet" href="/reserve/css/bootstrap.min.css"/>
<link rel="stylesheet" href="/reserve/css/custom.css"/>
</head>
<body>
<div class="container">
    <div id="body">
        <nav class="navbar navbar-expand-lg navbar-light bg-lights">
          <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
          </button>
          <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav">
              <li class="nav-item active">
                <a class="nav-link" href="home">Home <span class="sr-only">(current)</span></a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#">About</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#">Ideology</a>
              </li>
              <li class="nav-item">
                <a class="nav-link" href="#">Faq</a>
              </li>
               <li class="nav-item">
                <a class="nav-link" href="#">News</a>
              </li>
            </ul>
            <form class="form-inline my-2 my-lg-0 pull-right">
              <input class="form-control mr-sm-2" type="search" placeholder="Search">
              <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
            </form>
          </div>
        </nav>
        <!-- Site Body -->
        <div  id="content" class="container">
            <div class="row">

                <div id="leftMain" class="col-sm-3">
                <img src="/reserve/images/jim.png"width=100%/>

                </div>
                <div id="mainBody" class="col-sm-9 ">
                    <h2>Add Flights</h2>

                    <form action="add" method="post">
                        <div class="form-group">
                            <label for="flightNumber">Flight number</label>
                            <input type="text" class="form-control" name="flightNumber" placeholder="Flight number"/>
                        </div>
                        <div class="form-group">
                            <label for="operatingAirlines">Operating airlines</label>
                            <input type="text" class="form-control" name="operatingAirlines" placeholder="Operating airlines"/>
                        </div>
                        <div class="form-group">
                            <label for="departureCity">Departure city</label>
                            <input type="text" class="form-control" name="departureCity" placeholder="Departure city"/>
                        </div>
                        <div class="form-group">
                            <label for="arrivalCity">Arrival city</label>
                            <input type="text" class="form-control" name="arrivalCity" placeholder="Arrival city"/>
                        </div>

                        <div class="form-group">
                            <label for="dateOfDeparture">Date of departure</label>
                            <input type="Date" class="form-control" name="dateOfDeparture" placeholder="Date of departure"/>
                        </div>

                        <div class="form-group">
                            <label for="estimatedDepartureTime">Estimated departure time</label>
                            <input type="datetime-local" class="form-control" name="estimatedDepartureTime" placeholder="Estimated departure time"/>
                        </div>
                        <button type="submit" class="btn btn-primary">Save</button>
                    </form>

                </div>
            </div>
        </div>
    </div>

</div>
    <!-- JS, Popper.js, and jQuery -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"></script>
<script src="/reserve/js/bootstrap.min.js"></script>
</body>
</html>

Это ошибка, которую я получаю


Field error in object 'flight' on field 'estimatedDepartureTime': rejected value [2020-06-20T17:35]; codes 

[typeMismatch.flight.estimatedDepartureTime,typeMismatch.estimatedDepartureTime,typeMismatch.java.time.LocalDateTime,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: 

codes [flight.estimatedDepartureTime,estimatedDepartureTime]; arguments []; default message [estimatedDepartureTime]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.time.LocalDateTime' for property 'estimatedDepartureTime'; 

nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type

 [java.lang.String] to type [@javax.persistence.Column java.time.LocalDateTime] for value '2020-06-20T17:35'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2020-06-20T17:35]]]

``````

1 Ответ

0 голосов
/ 19 июня 2020

Вы можете попробовать использовать Spring The Formatter SPI для преобразования даты, выраженной как String, в LocalDateTime и наоборот.

public class DateTimeFormatters {

public static class LocalDateTimeFormatter implements Formatter<LocalDateTime> {

        @Override
        public LocalDateTime parse(String pattern, Locale locale) throws ParseException {
            return LocalDateTime.parse(pattern, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        }

        @Override
        public String print(LocalDateTime object, Locale locale) {
            return object.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        }
    }
}

И зарегистрируйте свой форматировщик, например

public class ApplicationConfig implements WebMvcConfigurer {
  ...
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addFormatter(new DateTimeFormatters.LocalDateTimeFormatter());
    }
  ...
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...