2017-04-18 53 views
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> 
+0

它適用於我的代碼。請,你可以添加控制檯輸出嗎? –

回答

0

歡迎SO。

變化

@Autowired 
private MoveRepository moveRepository = new MoveRepository(); 

@Autowired 
private MoveRepository moveRepository; 

的想法是,春季應通過依賴注入處理對象的實例。此外,請確保您的註釋是通過組件掃描(無論是在您的XML還是Java配置中)。

其他提示:

  • 也不是那麼有幫助的屬性一類的 相同的名稱命名move。更多的描述性命名對於下一個讀取你的代碼的人來說會更好。

  • 如果您的團隊允許,請嘗試Project Lombok至 擺脫樣板代碼。然後,你可以這樣做:

    public class Move { 
    
        @Getter 
        @Setter 
        private String move; 
    
    } 
    

    甚至更​​好:

    @Data 
    public class Move { 
    
        private String move; 
    
    } 
    
  • 考慮與@Repository註釋你的資料庫,如果你打算堅持到數據庫。這也將通過Spring爲您提供一些異常處理功能。

相關問題