无法设置单选按钮的值

时间:2018-12-02 22:53:49

标签: java html spring

我有下一个.html文件:

<body>

<form action="/add" method="post" class="w3-container w3-card-4 w3-light-grey w3-text-blue w3-margin" style="width: 50%">
    <h2 class="w3-center">Contact Us</h2>

    <div class="w3-row w3-section">
        <div class="w3-col" style="width:50px"><i class="w3-xxlarge fa fa-barcode"></i></div>
        <div class="w3-rest">
            <input class="w3-input w3-border" name="passportNumber" type="text" placeholder="Passport Data">
        </div>
    </div>

    <div class="w3-row w3-section">
        <div class="w3-col" style="width:50px"><i class="w3-xxlarge fa fa-male fa"></i></div>
        <div class="w3-rest">
            <input class="w3-radio" name="gender" type="radio" value="1" required>
        </div>
    </div>

    <div class="w3-row w3-section">
        <div class="w3-col" style="width:50px"><i class="w3-xxlarge fa fa-female"></i></div>
        <div class="w3-rest">
            <input class="w3-radio" name="gender" type="radio" value="2" required>
        </div>
    </div>    

    <div class="w3-container w3-margin">
        <input class="w3-button w3-blue" type="submit" value="Save"/>
    </div>
</form>

</body>

在此文件中,我设置了gender`value =“ 1” /“ 2”' 但是当我提交表单并进入控制器时:

@RequestMapping(value = "/add", method = RequestMethod.POST)
public ModelAndView savePerson(
        @RequestParam String gender
){
    System.out.println(gender);
    return null;
}

我总是得到gender值=“ on”

在这种情况下如何正确设置值?

1 个答案:

答案 0 :(得分:1)

我相信这里缺少的链接是省略了单选按钮的id属性。尝试添加唯一的ID,看看是否可以解决该问题。下面的示例:

<input class="w3-radio" name="gender" type="radio" id="male" value="male" required>
<input class="w3-radio" name="gender" type="radio" id="female" value="female" required>

:)希望这有助于您朝正确的方向前进。
-马修