0
我有一個非常簡單的對象調用移動:如何使用Spring/Thymeleaf窗體將POJO添加到列表中?
public class Move {
private String move;
public String getMove() {
return move;
}
public void setMove(String move) {
this.move = move;
}
}
我也有一個移動存儲庫(所有動作列表):
@Component
public class MoveRepository {
private List<Move>allMoves;
public void addMove(Move move){
allMoves.add(move);
}
public MoveRepository() {
this.allMoves = new ArrayList<>();
}
public void setAllMoves(List<Move> allMoves) {
this.allMoves = allMoves;
}
public List<Move> getAllMoves(){
return allMoves;
}
}
這裏是我的控制器:
@Controller
public class MoveController {
@Autowired
private MoveRepository moveRepository = new MoveRepository();
@GetMapping("/moveList")
public String listMoves (ModelMap modelMap){
List<Move> allMoves = moveRepository.getAllMoves();
modelMap.put("moves", allMoves);
return "moveList";
}
@GetMapping("/addMove")
public String addMoveForm(Model model) {
model.addAttribute("move", new Move());
return "addMove";
}
@PostMapping("/addMove")
public String addMoveSubmit(@ModelAttribute Move move) {
moveRepository.addMove(move); //Producing an error
return "moveAdded";
}
}
基本上,我想將使用網頁「/ addMove」上的表單提交的移動添加到Move Repository中移動allMoves的列表中。但是,只要點擊網頁上的提交按鈕,就會產生500個服務器錯誤。如果我從我的代碼刪除
moveRepository.addMove(move);
然後一切工作正常,但後來當然,此舉不會被添加到移動存儲庫。
我也有我的HTML(使用thymeleaf)代碼下面貼以供參考:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Add Move</title>
</head>
<body>
<h1>Add a move</h1>
<form action = "#" th:action="@{/addMove}" th:object="${move}" method = "post">
<p>Move: <input type = "text" th:field="*{move}"/></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</body>
</html>
它適用於我的代碼。請,你可以添加控制檯輸出嗎? –