首页 > 解决方案 > 提交值的空值

问题描述

关于

这是关于带有 Thymeleaf 模板引擎的 Spring Boot 2 框架

问题详情

尝试汇总输入页面中的单选按钮值时,输出页面显示空提交值。

枚举

public enum GameOptions {
    A,
    B,
    C
}

模型

public class UserData {
    private GameOptions _gameOption;

    public GameOptions get_gameOption() {
        return _gameOption;
    }

    public void set_gameOptions(GameOptions _gameOption) {
        this._gameOption = _gameOption;
    }
    
}

控制器

@Controller
public class myController {
    
    @GetMapping({"/input"})
    public String inputPage(Model model) {
        model.addAttribute("UserData", new UserData());
        return "input";
    }
    
    @PostMapping("/output")
    public String outputPage(UserData UserData, Model model) {
        model.addAttribute("UserData", UserData);
        return "output";
    }
}

模板 - 输入页面

<form method="post" th:action="@{/output}" th:object="${UserData}">
    <div th:each="model : ${T(com.example.demo.GameOptions).values()}">
        <div>
            <input type="radio" th:field="${UserData._gameOption}" th:value="${model}">
            <label th:for="${model}" th:text="${model}">model</label>
        </div>
    </div>
    <input type="submit" value="Submit" />
</form>

模板 - 输出页面

<p th:text="'id: ' + ${UserData._gameOption}" />

输出页面显示 id: null

标签: javaspringspring-boot

解决方案


您遇到的问题是由于您在 UserData 上的 getter 和 setter。

这将起作用

class UserData {
    private GameOptions gameOption;

    public GameOptions getGameOption() {
        return gameOption;
    }

    public void setGameOption(GameOptions gameOption) {
        this.gameOption = gameOption;
    }
}

输入.html

    ...
      <input type="radio" th:field="*{gameOption}" th:value="${model}">
    ...

输出.html

  <p th:text="'id:' + ${UserData.gameOption}" />

推荐阅读