如何接收LocalDate作为参数

我想插入一个简单的对象到数据库,但在我的控制器上,我无法发送LocalDate参数。如何接收LocalDate作为参数

错误说malformed request syntax, invalid request message framing, or deceptive request routing我很确定这个参数是LocalDate造成的。

我控制器

@RequestMapping(value = "/finance",method = RequestMethod.POST) 

public String postFinance(@ModelAttribute("finance")

Finance finance, Model model){

financeServices.targetActivate(finance);

model.addAttribute("targetSetStatus",true);

return "finance/finance";

}

金融实体

@Entity 

public class Finance {

@Id

@GeneratedValue(strategy = GenerationType.AUTO)

private Long id;

private LocalDate targetDate;

private Double targetAmount;

private LocalDate createdDate;

//getter setters //

}

编辑: - 我试图从形式插入,所以我的形式看起来像: -

<form class="form-horizontal" id="productForm" 

th:action="@{/finance}" method="post">

<div class="form-group">

<div th:if="${targetSetStatus}">

<div class="alert alert-success">

<p>New Target Has Been Set</p>

</div>

</div>

</div>

<div class="form-group">

<label class="control-label col-sm-3"

for="targetAmount">Target Amount:</label>

<div class="col-sm-9">

<input type="number" class="form-control"

placeholder="Targeted Amount"

name="targetAmount" id="targetAmount">

</div>

</div>

<div class="form-group">

<label class="control-label col-sm-3"

for="targetDate">Target Date:</label>

<div class="col-sm-9">

<input type="date" class="form-control"

placeholder="Targeted Date"

name="targetDate" id="targetDate">

</div>

</div>

<div class="form-group">

<div class="col-sm-offset-3 col-sm-9">

<button type="submit" class="btn btn-default">Set Target</button>

</div>

</div>

</form>

如果我用java.util.Date代替LocalDate它可以工作,但我想使用LocalDate它提供的java 8 API。

回答:

您必须注册一个自定义的JsonDeserializer。使用此代码:

import com.fasterxml.jackson.core.JsonParser; 

import com.fasterxml.jackson.core.JsonProcessingException;

import com.fasterxml.jackson.databind.DeserializationContext;

import com.fasterxml.jackson.databind.JsonDeserializer;

import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;

import java.time.LocalDate;

import java.time.format.DateTimeFormatter;

@JsonComponent

public class CustomJsonDeserializer {

/*public static class Serializer extends JsonSerializer<LocalDate> {

@Override

public void serialize(LocalDate localDate, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {

}

}*/

public static class LocalDateDeserializer extends JsonDeserializer<LocalDate> {

@Override

public LocalDate deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {

String strDate = jsonParser.getValueAsString();

if (strDate == null || strDate.isEmpty()) {

return null;

}

return LocalDate.parse(strDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));

}

}

}

看看这个链接Custom JSON Serializers and Deserializers

以上是 如何接收LocalDate作为参数 的全部内容, 来源链接: utcz.com/qa/265840.html

回到顶部