【问题标题】:How do I add a POJO to a list using Spring/Thymeleaf form?如何使用 Spring/Thymeleaf 表单将 POJO 添加到列表中?
【发布时间】:2017-04-18 19:05:07
【问题描述】:

我有一个非常简单的对象,叫做 Move:

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”上的表单提交的移动添加到移动存储库中的所有移动列表中。但是,每当我单击网页上的提交按钮时,它都会产生 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>

【问题讨论】:

  • 它适用于我的代码。请问,你能添加控制台输出吗?

标签: java spring thymeleaf


【解决方案1】:

欢迎来到 SO。

改变

@Autowired
private MoveRepository moveRepository = new MoveRepository();

@Autowired
private MoveRepository moveRepository;

这个想法是 Spring 应该通过依赖注入来处理对象的实例化。此外,请确保通过组件扫描(在您的 XML 或 Java 配置中)拾取您的注释。

其他提示:

  • 将名为 move 的属性放在 同名。更具描述性的命名会更好 下一个人阅读您的代码。

  • 如果您的团队允许,请尝试Project Lombok 摆脱样板代码。然后你可以这样做:

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

    甚至更好:

    @Data
    public class Move {
    
       private String move;
    
    } 
    
  • 如果您打算持久保存到数据库,请考虑使用 @Repository 注释您的存储库。这还将通过 Spring 为您提供一些异常处理功能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 2021-04-06
    • 1970-01-01
    • 2017-10-20
    相关资源
    最近更新 更多