我正在嘗試從 home.html 模板發布文本
<form th:action="@{/process_addText}" th:object="${textzz}" method="post" >
<input type="text" th:field="*{text}" />
<button type="submit" class="btn btn-info">Add</button>
</form>
這是我的控制器
@PostMapping("/process_addText")
public String processAddText(Text text1) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
User myUser=userRepo.findByEmail(name);
text1.setUser(myUser);
textRepo.save(text1);
return "redirect:/home";
}
@GetMapping("/home")
public String mySuccess(Model model) {
model.addAttribute("textzz",new Text());
LOGGER.info("verif===" model.toString());
return "home";
}
這是我的文本類:
@Entity
@Table(name = "texts")
public class Text {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idText;
@OneToOne
@JoinColumn(name = "id", referencedColumnName = "id")
private User user;
private String text;
}
當我嘗試從 home.html 發布“文本”值時,出現此錯誤:
WARN 680 --- [nio-8088-exec-7] .wsmsDefaultHandlerExceptionResolver:已解決 [org.springframework.beans.TypeMismatchException:無法將“java.lang.String”型別的值轉換為所需的“com.myblog.app”型別。模型.文本'; 嵌套例外是 org.springframework.core.convert.ConversionFailedException:無法從型別 [java.lang.String] 轉換為型別 [java.lang.Long] 的值 'qvefd';嵌套例外是 java.lang.NumberFormatException: For input string: "qvefd"]
我不知道為什么會得到這個,因為型別是正確的
更新:當我洗掉輸入并在我的資料庫中發布(沒有文本)時,我得到正確的行(對于文本 ID 和用戶的外鍵),當然文本值 = NULL。所以問題可能出在輸入型別上。
uj5u.com熱心網友回復:
您的控制器方法接受一個Text物體,但您的前端表單僅在請求正文中發送一個簡單String的 post 請求。
然后 Spring 無法將其String轉換為Text物件。
所以你的控制器方法應該是
@PostMapping("/process_addText")
public String processAddText(String text) {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();
User myUser=userRepo.findByEmail(name);
Text text1 = textRepo.findByUser(myUser);
if (text1 == null){
text1 = new Text();
text1.setUser(myUser);
}
text1.setText(text);
textRepo.save(text1);
return "redirect:/home";
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/415013.html
標籤:
上一篇:nodejs中的Spring物體
