我无法将输入的日期值从窗体传递到控制器。所有值都被正确地传递和存储在数据库中,但日期为空。创建一个javadate对象并手动设置它是可行的,所以我认为问题出在前端格式化上。
以下是带有thymeleaf语法的html代码:
<form th:action="@{/register}" method="post" th:object="${user}" id="userInfo">
...
<h4>Enter Payment Information</h4>
<div th:object="${card}">
<div class="col-12">
<label for="cardType" id="cardType"><strong>Card
type:</strong></label> <select class="form-select" th:field="*{cardType}">
<option th:value="None">Select one:</option>
<option th:value="Visa" th:text="Visa"></option>
<option th:value="Mastercard" th:text="Mastercard"></option>
<option th:value="Discover" th:text="Discover"></option>
<option th:value="AmericanExpress" th:text="AmericanExpress"></option>
</select>
</div>
<div class="col-12">
<label for="card-number" id="cardNumberLabel"><strong>Card
number:</strong></label> <input type="text" th:field="*{cardNumber}" class="form-control"
id="card-number" name="card-number"
pattern="^\d{16}$"
title="Card number must be 16 digits long."
value="">
</div>
<div class="col-12 mb-2">
<label for="exp" id="expLabel"><strong>Expiration
date:</strong></label> <input type="date" th:value="*{expirationDate}" class="form-control" id="exp"
name="exp"
value="">
</div>
</div>
...
</form>
以下是控制器(为了简洁起见,我省略了一些细节,但保留了相关部分):
@GetMapping(value={"/register", "register.html"})
public String displayForm(Model model) {
// process form data and add user to db
User user = new User();
PaymentCard card = new PaymentCard();
model.addAttribute("user", user);
model.addAttribute("card", card);
return "register";
}
@PostMapping(value={"/register", "register.html"})
public String createAccount(@ModelAttribute("user") User user, @ModelAttribute("card") PaymentCard card) {
User tempUser = new User();
PaymentCard tempCard = new PaymentCard();
tempCard.setUser(tempUser);
tempCard.setPaymentCardId(card.getPaymentCardId());
tempCard.setCardType(card.getCardType());
tempCard.setCardNumber(card.getCardNumber());
//tempCard.setExpirationDate(card.getExpirationDate()); <--- this returns null so I get a NPE
Date tempDate = new Date(2020, 11, 12); <--- dummy date that works and is saved to db correctly
tempCard.setExpirationDate(tempDate);
cardRepo.save(tempCard);
return "confirmregistration";
}
支付卡pojo的开始:
@Entity
@Table(name = "payment_card", catalog = "bookstore")
public class PaymentCard implements java.io.Serializable {
@Id
@Column(name = "PaymentCardID", unique = true, nullable = false)
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int paymentCardId;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "UserID")
private User user;
@Column(name = "cardNumber", nullable = false)
private String cardNumber; // int and long aren't big enough to hold 16 digits
@Column(name = "cardType", nullable = false, length = 20)
private String cardType;
@Temporal(TemporalType.DATE)
@Column(name = "expirationDate", nullable = false, length = 10)
private Date expirationDate;
...
}
1条答案
按热度按时间w41d8nur1#
试试这个:
如果这不起作用,试着像这样获得单独的字段: