如何将类型为’java.lang.String’的值转换为所需类型’java.util.Date’?

huangapple go评论79阅读模式
英文:

How to convert value of type 'java.lang.String' to required type 'java.util.Date'?

问题

My Flight Code:

import java.sql.Timestamp;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import org.springframework.format.annotation.DateTimeFormat;

@Entity
@Table(name = "FLIGHT")
public class Flight {
    @Column(name = "flight_number")
    private String flightNumber;
    @Column(name = "operating_airlines")
    private String operatingAirlines;
    @Column(name = "arrival_city")
    private String arrivalCity;
    @Column(name = "departure_city")
    private String departureCity;
    @Column(name = "date_of_departure")
    @DateTimeFormat(pattern = "dd-MM-yyyy")
    private Date dateOfDeparture;
    @Column(name = "estimated_departure_time")
    private Timestamp estimatedDepartureTime;

    // Contains getters and setters for these properties
}

In my Flight Repository (Interface):

package com.nischal.flightreservation.repos;

import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.nischal.flightreservation.entities.Flight;

public interface FlightRepository extends JpaRepository<Flight, Integer> {
    @Query(value = "select * from FLIGHT where departure_city=:departureCity and " +
    "arrival_city=:arrivalCity and date_of_departure=:dateOfDeparture", nativeQuery = true)
    List<Flight> findFlights(@Param("departureCity") String from, @Param("arrivalCity") String to, 
    @Param("dateOfDeparture") Date departureDate);
}

In my Flight 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.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.nischal.flightreservation.entities.Flight;
import com.nischal.flightreservation.repos.FlightRepository;

@Controller
public class FlightController {
    @Autowired
    private FlightRepository flightRepository;
    
    @RequestMapping("/findFlights")
    public String findFlights(@RequestParam(required = false, name = "from") String from,
                              @RequestParam(required = false, name = "to") String to,
                              @RequestParam(required = false, name = "departureDate") 
                              @DateTimeFormat(pattern = "dd-MM-yyyy") Date departureDate,
                              ModelMap modelMap) {
        List<Flight> flights = flightRepository.findFlights(from, to, departureDate);
        modelMap.addAttribute("flights", flights);
        return "displayFlights";
    }
}

In my findFlights.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Search the Flights</title>
</head>
<body>
    <form action="findFlights" method="post">
        <pre>
            From: <input type="text" name="from"/>
            To  : <input type="text" name="to"/>
            Departure Date: <input type="date" name="departureDate"/>
            <input type="submit" value="Search"/>
        </pre>
    </form>
</body>
</html>

The displayFlights.jsp to display available flights:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Available Flights</title>
</head>
<body>
    <h2>Flights</h2>
    <table>
        <tr>
            <th>Airlines</th>
            <th>Departure City</th>
            <th>Arrival City</th>
            <th>Departure Time</th>
        </tr>
        <c:forEach items="${flights}" var="flight">
            <tr>
                <td>${flight.operatingAirlines}</td>
                <td>${flight.departureCity}</td>
                <td>${flight.arrivalCity}</td>
                <td>${flight.estimatedDepartureTime}</td>
                <td><a href="showCompleteReservation?flightId=${flight.id}">Select</a></td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>

If anyone wants more details, I can also provide the GitHub link to this project.

英文:

My Flight Code:

import java.sql.Timestamp;

import java.util.Date;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.Table;

import org.springframework.format.annotation.DateTimeFormat;

@Entity

@Table(name = &quot;FLIGHT&quot;)

public class Flight
{

@Column(name = &quot;flight_number&quot;)

private String flightNumber;

@Column(name = &quot;operating_airlines&quot;)

private String operatingAirlines;

@Column(name = &quot;arrival_city&quot;)

private String arrivalCity;

@Column(name = &quot;departure_city&quot;)

private String departureCity;

@Column(name = &quot;date_of_departure&quot;)

@DateTimeFormat(pattern = &quot;dd-MM-yyyy&quot;)

private Date dateOfDeparture;

@Column(name = &quot;estimated_departure_time&quot;)

private Timestamp estimatedDepartureTime;

and contains getters and setters for this:

and In my Flight Repository(Interface) I have:

package com.nischal.flightreservation.repos;

import java.util.Date;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.data.jpa.repository.Query;

import org.springframework.data.repository.query.Param;

import com.nischal.flightreservation.entities.Flight;


public interface FlightRepository extends JpaRepository&lt;Flight, Integer&gt; {

@Query(value = &quot;select * from FLIGHT where departure_city=:departureCity and 
arrival_city=:arrivalCity and date_of_departure=:dateOfDeparture&quot;, nativeQuery = true)

List&lt;Flight&gt; findFlights(@Param(&quot;departureCity&quot;) String from, @Param(&quot;arrivalCity&quot;) String 
to, @Param(&quot;dateOfDeparture&quot;) Date departureDate);

}

and they are correctly mapped with the database tables.

and in my FlightControllers I have:

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.ModelMap;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;

import com.nischal.flightreservation.entities.Flight;

import com.nischal.flightreservation.repos.FlightRepository;

@Controller

public class FlightController {

@Autowired

private FlightRepository flightRepository;

@RequestMapping(&quot;/findFlights&quot;)

public String findFlights(@RequestParam(required = false,name = &quot;from&quot;) String from,
@RequestParam(required = false,name = &quot;to&quot;) String to,@RequestParam(required = false, name = 
&quot;departureDate&quot;) @DateTimeFormat(pattern = &quot;dd-MM-yyyy&quot;) Date departureDate ,ModelMap 
modelMap) 

{
  
List&lt;Flight&gt; flights = flightRepository.findFlights(from, to, departureDate);
	
modelMap.addAttribute(&quot;flights&quot;,flights);
	
return &quot;displayFlights&quot;;
	
}

}

In my findFlights.jsp I have following code:

&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=UTF-8&quot;
pageEncoding=&quot;UTF-8&quot;%&gt;

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta charset=&quot;UTF-8&quot;&gt;
&lt;title&gt;Search the Flights&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;form action = &quot;findFlights&quot; method = &quot;post&quot;&gt;
	&lt;pre&gt;
		From: &lt;input type = &quot;text&quot; name = &quot;from&quot;/&gt;
		To  : &lt;input type = &quot;text&quot; name = &quot;to&quot;/&gt;
		Departure Date:&lt;input type = &quot;date&quot; name = &quot;departureDate&quot;/&gt;
		&lt;input type = &quot;submit&quot; value = &quot;Search&quot;/&gt;
	&lt;/pre&gt;
&lt;/form&gt;

</body>
</html>

and displayFlights is responsible to display the available flights based on the search and the code is :

&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta charset=&quot;UTF-8&quot;&gt;
&lt;title&gt;Available Flights&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h2&gt;Flights&lt;/h2&gt;
&lt;table&gt;
	&lt;tr&gt;
		&lt;th&gt;Airlines&lt;/th&gt;
		&lt;th&gt;Departure City&lt;/th&gt;
		&lt;th&gt;Arrival City&lt;/th&gt;
		&lt;th&gt;Departure Time&lt;/th&gt;
	&lt;/tr&gt;
	&lt;c:forEach items = &quot;${flights}&quot; var = &quot;flight&quot;&gt;
	&lt;tr&gt;
		&lt;td&gt;flight.operatingAirlines&lt;/td&gt;
		&lt;td&gt;flight.departureCity&lt;/td&gt;
		&lt;td&gt;flight.arrivalCity&lt;/td&gt;
		&lt;td&gt;flight.estimatedDepartureTime&lt;/td&gt;
		&lt;td&gt;&lt;a href = &quot;showCompleteReservation?flightId=${flight.id }&quot;&gt;Select&lt;/a&gt;
	&lt;/tr&gt;
	&lt;/c:forEach&gt;
	
&lt;/table&gt;

</body>
</html>

But whenever i hit Search button it yields errors saying:

如何将类型为’java.lang.String’的值转换为所需类型’java.util.Date’?

If anyone wants more detail then i can also provide the github link of this project.

答案1

得分: 0

请求参数中,您会获得一个字符串,您需要一个格式化程序将其转换为日期,您可以使用DateTimeFormatter。

@PostMapping("/date")
public void date(@RequestParam("date")
  @DateTimeFormat(pattern = "dd.MM.yyyy") Date date) {
    // ...您需要将您的Java日期映射到SQL日期

或者您可以创建一个格式化程序类并使用它。

处理之后,

在Hibernate中,有一个temporal注解可以实现这一点。
这里是一个示例

@Temporal(TemporalType.DATE)
private java.util.Date creationDate;
英文:

In request parameter you will get string you need a formatter to convert it to date you can use DateTimeFormatter

@PostMapping(&quot;/date&quot;)
public void date(@RequestParam(&quot;date&quot;) 
  @DateTimeFormat(pattern = &quot;dd.MM.yyyy&quot;) Date date) {
    // ...You need to map your java date to SQL date 

Or you can create a formatter class and use it.

After process

In hibernate there is temporal annotation to do it
Here is a sample

@Temporal(TemporalType.DATE)
private java.util.Date creationDate

答案2

得分: 0

我能在错误页面中看到“对于值'2020-02-02'...”。

您已经在POJO中使用了@DateTimeFormat(pattern = "dd-MM-yyyy")注解正确设置了模式。但是,默认情况下,JSP正在使用"yyyy-MM-dd"。您可以在这里阅读关于无法更改格式的内容。

我认为html中的输入格式取决于本地语言浏览器配置。

如果您使用@Temporal注解,就像Karanjot说的那样,它会自动将Java日期映射到SQL日期。但默认格式仍然是yyyy-MM-dd。您需要同时使用temporal和format注解。

问题是在您的“前端”中,您正在使用"yyyy-MM-dd",而您的findFlights方法期望"dd-MM-yyyy"。

我已经观察到您正在从控制器直接调用存储库。这是不良做法。在控制器和存储库之间创建一个服务。您的控制器将接收"yyyy-MM-dd"。将其转换并以正确的格式发送到服务。

为了避免向findFlights方法(以及其他方法)传递过多的参数,考虑使用对象和DTOs。

英文:

I can read in the error page "for value '2020-02-02'....".

You have set correctly the pattern in the POJO with the annotation @DateTimeFormat(pattern = "dd-MM-yyyy"). But, by default, JSP are using "yyyy-MM-dd". Here you can read about that is impossible to change the format.

I think that the input format in html will depends on local language browser configuration.

If you use the @Temporal annotation, like Karanjot said, it will map automatically java date to sql date. But the default format still being yyyy-MM-dd. You need both: temporal and format annotations.

The problem is that, in your "front", you are using "yyyy-MM-dd" and your findFlights method expect "dd-MM-yyyy".

I have observe that you are calling the repository directly from controller. Bad practice. Create a service between controller and repository. Your controller will receive "yyyy-MM-dd". Convert it and send to service with correct format.

And to avoid too much arguments to findFlights method (and another), consider to use objects and DTOs.

答案3

得分: 0

我必须在Model类Flight中导入两个类,分别是Temporal和TemporalType。
以下是完整的解决方案。

import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Temporal(TemporalType.DATE)
private Date dateOfDeparture;
英文:

I have to import two Classes namely Temporal and TemporalType in Model class Flight.
Here, is the complete solution.

import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Temporal(TemporalType.DATE)
private Date dateOfDeparture;

huangapple
  • 本文由 发表于 2020年4月11日 12:27:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/61152138.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定