2016-10-31 10 views
0

私はSpring MVCを発見し始めたばかりで、この単純なプロジェクトに悩まされています。テンプレートindex1.htmlでは、プレーヤーオブジェクト(th:object = "$ {player}")とフィールド値(th:field = "{playerId}")、(th:field = " {playerName}")can can解決されません。 ($ {player.playerId})と($ {player.playerName})のテンプレートindex2.htmlと同じ状況です。何がその理由かもしれないかを提案できますか?Spring MVC thymeleafがオブジェクトの属性とフィールドを解決できない

PlayerController.java

@Controller 
public class PlayerController { 

Logger log = LoggerFactory.getLogger(this.getClass()); 

@RequestMapping(value = "/create", method = RequestMethod.GET) 
public String showForm(Model model) { 
    model.addAttribute("player", new Player()); 
    return "create"; 
} 

@RequestMapping(value = "/create", method = RequestMethod.POST) 
public String processForm(@ModelAttribute Player player, Model model) { 
    model.addAttribute("player", player); 

    String info = String.format("Player Submission: playerId = %d, playerName = %s", 
      player.getPlayerId(), player.getPlayerName()); 
    log.info(info); 
    return "view"; 
} 

}

モデル

public class Player{ 

private int playerId; 
private String playerName; 

.... getters and setters 
} 

ビュー

<!DOCTYPE html> 
 
<html lang="en" xmlns:th="http://www.thymeleaf.org"> 
 

 
<head> 
 
    <meta http-equiv="Content-Type" content="text/html" charset="UTF-8" > 
 
    <title>Form Submission</title> 
 

 
</head> 
 
<body> 
 
    <h1>Player</h1> 
 
    <form action = "#" th:action="@{/create}" th:object="${player}" method="post"> 
 
     <p>Id: <input type="text" th:field="*{playerId}" /></p> 
 
     <p>Name: <input type="text" th:field="*{playerName}" /></p> 
 
     <p><input type="submit" value="Add" /></p> 
 
    </form> 
 

 
</body> 
 
</html>

<!DOCTYPE html> 
 
<html lang="en" xmlns:th="http://www.thymeleaf.org"> 
 
<head> 
 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
 
    <title>Player info</title> 
 
</head> 
 
<body> 
 

 
<p th:text="'ID: ' + ${player.playerId}" /> 
 
<p th:text="'Name: ' + ${player.playerName}" /> 
 

 
</body> 
 
</html>

プロジェクト構造 Click to see the Project Structure

+0

?/resource/templatesにする必要があります。 – cralfaro

+0

@cralfaroはい、htmlファイルは/ resources/templatesにあります。上記のプロジェクト構造のスクリーンショットを添付しました。 –

答えて

0

あなたのビューページへのHTTP要求を転送するreturn "redirect:を試してみてください。私はお勧め

@RequestMapping(value = "/create", method = RequestMethod.POST) 
    public String processForm(@ModelAttribute Player player, Model model) { 
     model.addAttribute("player", player); 

     String info = String.format("Player Submission: playerId = %d, playerName = %s", 
       player.getPlayerId(), player.getPlayerName()); 
     log.info(info); 
     return "redirect:view"; 
     // OR return "redirect:/view"; 
    } 

別のアプローチは、次のとおりです。あなたはあなたのhtmlファイルを見つけたん

@RequestMapping(value = "/create", method = RequestMethod.POST) 
public String processForm(@ModelAttribute("player")) { 

    log.info(info); 
    return "redirect:/view"; 
} 
+0

私はあなたのアプローチを試みたが、これはうまくいかなかった。 –

関連する問題