Ich habe eine sehr einfach als Objekt zu verschieben:Wie füge ich einen POJO zu einer Liste mit Spring/Thymeleaf-Formular hinzu?
public class Move {
private String move;
public String getMove() {
return move;
}
public void setMove(String move) {
this.move = move;
}
}
Ich habe auch eine Bewegung Repository (eine Liste aller Bewegungen):
@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;
}
}
Hier ist mein Controller:
@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";
}
}
Im Grunde möchte ich den Zug, der mit dem Formular auf der Webseite "/ addMove" eingereicht wurde, zur Liste der Züge allMoves im Move Repository hinzufügen. Es erzeugt jedoch einen 500-Server-Fehler, wenn ich auf die Absenden-Schaltfläche auf der Webseite klicke. Wenn ich die
moveRepository.addMove(move);
von meinem Code löschen dann funktioniert alles in Ordnung, aber dann natürlich die Bewegung nicht auf den Zug-Repository hinzugefügt bekommen.
Ich habe auch meine HTML (mit thymeleaf) Code unten als Referenz geschrieben:
<!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>
funktioniert es für mich mit Ihrem Code. Können Sie bitte die Konsolenausgabe hinzufügen? –