2016-10-31 40 views
0

我剛剛開始發現Spring MVC並陷入了這個簡單的項目。在模板index1.html播放器對象(th:object =「$ {player}」)和字段值(th:field =「{playerId}」)中,(th:field =「 {playerName}」)can沒有解決。模板index2.html與($ {player.playerId})和($ {player.playerName})相同的情況。你能提出可能的原因嗎?Spring MVC百里香葉無法解析對象屬性和字段

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

,你在哪裏已經找到你的HTML文件?應該是ito/resources/templates – cralfaro

+0

@cralfaro是的,html文件位於/ resources/templates中。我附上了上面的Project結構屏幕截圖。 –

回答

0

嘗試return "redirect:的http請求傳送到您的視圖頁面。

@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"; 
    } 

另一種方法,我建議是:

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

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

我試過你的方法,但是這沒有奏效。 –