java spring - 发布带有附加值

时间:2017-05-15 14:23:17

标签: java html spring post thymeleaf

我已经实施了注册流程,您可以通过邮寄请求将用户数据发送到控制器。

post请求正常,但是现在我想将另一个值(role,Long)从表单传递给不是用户模型属性的控制器。

那部分不起作用。 有谁知道为什么?

HTML:

<form action="add_user" method="post" class="form-horizontal" th:object="${user}">
                    <div class="form-group">
                        <div class="col-sm-offset-1 col-sm-10">
                            <input th:field="*{username}" class="form-control" placeholder="Person ID" type="text" name="id" id="id"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-1 col-sm-10">
                            <input th:field="*{firstName}" class="form-control" placeholder="First Name" type="text" name="firstname" id="firstname"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-1 col-sm-10">
                            <input th:field="*{lastName}" class="form-control" placeholder="Last Name" type="text" name="lastname" id="lastname"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-1 col-sm-10">
                            <input th:field="*{password}" class="form-control" placeholder="Password" type="password" name="password" id="password"/>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-1 col-sm-10">
                            <select th:field="${role}" class="form-control" id="role">
                                <option value="1">Admin</option>
                                <option value="2" >User</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-1 col-sm-10">
                            <button type="submit" class="btn btn-success" value="Submit">Save</button>
                        </div>
                    </div>
                </form>

控制器:

    @RequestMapping(value = "/users", method = RequestMethod.GET) 
    public String showUsers(Model model) 
        model.addAttribute("user", new User());
        model.addAttribute("role", new Long(2));
        return "users";
}

@RequestMapping(value = "/add_user", method = RequestMethod.POST)
public String handleNewUser(@ModelAttribute("user") User user, BindingResult bindingResult, Model model, long role) {
    if (user != null) {
        System.out.println(role);
        userService.save(user);
    }
    return "redirect:/users";
}

1 个答案:

答案 0 :(得分:1)

th:field="${role}"表示模型对象中的字段名称,而不是其值。你可能想写th:value="${role}"而不是这个。