【发布时间】:2016-06-09 05:54:45
【问题描述】:
我正在尝试为我的应用程序实现创建/编辑用户。
在我的控制器上,我有以下方法来创建新用户或编辑现有用户。
@RequestMapping(value = "/admin/createUser", method = RequestMethod.GET)
public void createtUser(ModelMap model) throws IOException, Exception {
model.addAttribute("pojo", new UserPojo());
model.addAttribute("roles", initializeProfiles());
}
@ModelAttribute("roles")
public List<UserProfile> initializeProfiles() {
return userProfileService.findAll();
}
@RequestMapping(value = "/admin/createUser", method = RequestMethod.POST)
public String createUserPost(ModelMap model, @Valid @ModelAttribute("pojo") UserPojo pojo, BindingResult result, Errors errors) {
if (errors.hasErrors()) {
System.out.println("There are errors");
return "/admin/createUser";
}
System.out.println(pojo.getProfiles());
try {
userService.save(pojo.getSsoId(),
pojo.getFirstName(),
pojo.getLastName(),
pojo.getEmail(),
pojo.getProfiles(),
pojo.getPassword());
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
model.addAttribute("success", "User " + pojo.getSsoId() + " has been created successfully");
return "redirect:/admin/homeAdmin";
}
UserPojo 模型是:
public class UserPojo {
private String id;
private String ssoId;
private String firstName;
private String lastName;
private String email;
private String password;
private String state;
private Set<UserProfile> profiles;
// getters and setters
UserProfile pojo 是:
@Entity
@Table(name="userProfile")
public class UserProfile extends BasePojo {
@Column(name="type", length=15, unique=true, nullable=false)
private String type = UserProfileType.USER.getUserProfileType();
// getter and setter
UserProfileType 枚举是:
public enum UserProfileType {
USER("USER"),
DBA("DBA"),
ADMIN("ADMIN");
String type;
private UserProfileType(String userProfileType) {
this.type = userProfileType;
}
public String getUserProfileType() {
return type;
}
在我的 createUser.html 页面上,我选择了以下用户:
<select class="form-control" th:field="*{profiles}" name="profiles" multiple="multiple">
<option th:each="role : ${roles}"
th:value="${{profiles}}"
th:text="${role.type}">
</option>
</select>
问题是,当我提交数据时,控制器在 UserPojo 配置文件字段上看到 null 并且不会保留分配的用户配置文件。
如何解决这个问题?
【问题讨论】:
-
这是创建用户的表单提交吗,如果是,则尝试将 name 属性添加到每个表单字段,并且该名称应与您的 pojo 中定义的变量匹配。跨度>
标签: java spring spring-mvc crud thymeleaf