Spring MVC 控制器,在两个方法之间传递一个 bean
Spring MVC Controller , pass a bean between two method
我已经通过开发一个简单的 SPRING MVC 应用程序开始学习 Spring MVC。
我创建了一个 JSP 文件用于列表 - 像这样编辑用户列表:
当我点击 "Edit" link(来自列表项)时,表格应该由项目信息填充,因此用户可以编辑信息并保存项目(请注意,这表单用于创建/编辑项目)
这是与 JSP 文件相关的代码:
<c:url var="addAction" value="/admin/users/add"></c:url>
<form:form action="${addAction}" commandName="user">
<table>
<c:if test="${!empty user.adminName}">
<tr>
<td><form:label path="id">
<spring:message text="ID" />
</form:label></td>
<td><form:input path="id" readonly="true" size="8"
disabled="true" /> <form:hidden path="id" /></td>
</tr>
</c:if>
<tr>
<td><form:label path="adminName">
<spring:message text="Name" />
</form:label></td>
<td><form:input path="adminName" /></td>
</tr>
<tr>
<td><form:label path="adminEmail">
<spring:message text="adminEmail" />
</form:label></td>
<td><form:input path="adminEmail" /></td>
</tr>
<tr>
<td><form:select path="groups" items="${groupList}" /></td>
</tr>
<tr>
<td colspan="2"><c:if test="${!empty user.adminName}">
<input type="submit" value="<spring:message text="Edit Person"/>" />
</c:if> <c:if test="${empty user.adminName}">
<input type="submit" value="<spring:message text="Add Person"/>" />
</c:if></td>
</tr>
</table>
</form:form>
<br>
<div class="bs-example">
<table class="table">
<thead>
<tr>
<th>Row</th>
<th>First Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<c:forEach var="i" items="${users}">
<tr>
<td>${i.id}</td>
<td>${i.firstName}</td>
<td>${i.adminEmail}</td>
<td><a href="<c:url value='/admin/users/edit/${i.id}'/>">Edit</a></td>
<td><a href="<c:url value='/admin/users/remove/${i.id}'/>">Delete</a></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
我的控制器方法是:
@Controller
@RequestMapping(value = "/admin/users/")
public class UserController {
private static final Logger LOGGER = LoggerFactory
.getLogger(UserController.class);
@Autowired
UserService userService;
@Autowired
GroupService groupService;
@Autowired
LabelUtils messages;
@Autowired
private BCryptPasswordEncoder passwordEncoder;
// @PreAuthorize("hasRole('STORE_ADMIN')")
@RequestMapping(value = "list.html", method = RequestMethod.GET)
public String displayUsers(Model model) throws Exception {
List<User> users = userService.listUser();
List<Group> groups = groupService.list();
List<String> groupList = new ArrayList<String>();
model.addAttribute("users", users);
model.addAttribute("user", new User());
for (Group group : groups) {
groupList.add(group.getGroupName());
}
model.addAttribute("groupList", groupList);
return "admin/userAdmin";
}
@RequestMapping("remove/{id}")
public String removePerson(@PathVariable("id") int id) {
User user = userService.getById((long) id);
try {
userService.delete(user);
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "redirect:/admin/users/list.html";
}
// For add and update person both
@RequestMapping(value = "add" , method = RequestMethod.POST)
public String addPerson(@ModelAttribute("user") User user,
BindingResult result) {
if (result.hasErrors()) {
return "error";
}
try {
if (user.getId() == 0) {
// new person, add it
this.userService.create(user);
} else {
// existing person, call update
this.userService.saveOrUpdate(user);
}
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "redirect:/admin/users/list.html";
}
@RequestMapping(value = "edit/{id}" )
public String editPerson(@PathVariable("id") int id , Model model) {
// Prepare Groups
List<Group> groups = groupService.list();
List<String> groupList = new ArrayList<String>();
for (Group group : groups) {
groupList.add(group.getGroupName());
}
model.addAttribute("groupList", groupList);
model.addAttribute("user", this.userService.getById((long) id));
model.addAttribute("users", this.userService.list());
return "admin/userAdmin";
}
}
问题是当我点击编辑 link 时,表单由项目信息正确填充,因此用户可以编辑检索到的数据,但是对象 "user" 从方法 [=38] 检索=] 在控制器中的 "addPerson" 方法中(
代码行:model.addAttribute("user", this.userService.getById((long) id));在 editPerson 方法中)
让所有其他字段为空,因此当我合并数据时,保存操作失败。
示例:用户项目有一个其他字段 "AdminAPassword" 未在 JSP 中打印并且用户未更改,当从表单中检索数据时,该字段为空。
你能帮忙吗
提前致谢
你的问题有点不清楚,我会根据你的标题来处理。我的理解是,您希望在控制器内的方法之间共享 user bean。您可以通过使用 @SessionAttributes
注释您的控制器来实现此目的
@SessionAttributes("user")
@Controller
@RequestMapping(value = "/admin/users/")
public class UserController {
使用此设置,名称与 @SessionAttributes 中列出的属性匹配的所有模型属性将在后续请求中保留。您可以了解更多 here
我已经通过开发一个简单的 SPRING MVC 应用程序开始学习 Spring MVC。
我创建了一个 JSP 文件用于列表 - 像这样编辑用户列表:
当我点击 "Edit" link(来自列表项)时,表格应该由项目信息填充,因此用户可以编辑信息并保存项目(请注意,这表单用于创建/编辑项目)
这是与 JSP 文件相关的代码:
<c:url var="addAction" value="/admin/users/add"></c:url>
<form:form action="${addAction}" commandName="user">
<table>
<c:if test="${!empty user.adminName}">
<tr>
<td><form:label path="id">
<spring:message text="ID" />
</form:label></td>
<td><form:input path="id" readonly="true" size="8"
disabled="true" /> <form:hidden path="id" /></td>
</tr>
</c:if>
<tr>
<td><form:label path="adminName">
<spring:message text="Name" />
</form:label></td>
<td><form:input path="adminName" /></td>
</tr>
<tr>
<td><form:label path="adminEmail">
<spring:message text="adminEmail" />
</form:label></td>
<td><form:input path="adminEmail" /></td>
</tr>
<tr>
<td><form:select path="groups" items="${groupList}" /></td>
</tr>
<tr>
<td colspan="2"><c:if test="${!empty user.adminName}">
<input type="submit" value="<spring:message text="Edit Person"/>" />
</c:if> <c:if test="${empty user.adminName}">
<input type="submit" value="<spring:message text="Add Person"/>" />
</c:if></td>
</tr>
</table>
</form:form>
<br>
<div class="bs-example">
<table class="table">
<thead>
<tr>
<th>Row</th>
<th>First Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<c:forEach var="i" items="${users}">
<tr>
<td>${i.id}</td>
<td>${i.firstName}</td>
<td>${i.adminEmail}</td>
<td><a href="<c:url value='/admin/users/edit/${i.id}'/>">Edit</a></td>
<td><a href="<c:url value='/admin/users/remove/${i.id}'/>">Delete</a></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
我的控制器方法是:
@Controller
@RequestMapping(value = "/admin/users/")
public class UserController {
private static final Logger LOGGER = LoggerFactory
.getLogger(UserController.class);
@Autowired
UserService userService;
@Autowired
GroupService groupService;
@Autowired
LabelUtils messages;
@Autowired
private BCryptPasswordEncoder passwordEncoder;
// @PreAuthorize("hasRole('STORE_ADMIN')")
@RequestMapping(value = "list.html", method = RequestMethod.GET)
public String displayUsers(Model model) throws Exception {
List<User> users = userService.listUser();
List<Group> groups = groupService.list();
List<String> groupList = new ArrayList<String>();
model.addAttribute("users", users);
model.addAttribute("user", new User());
for (Group group : groups) {
groupList.add(group.getGroupName());
}
model.addAttribute("groupList", groupList);
return "admin/userAdmin";
}
@RequestMapping("remove/{id}")
public String removePerson(@PathVariable("id") int id) {
User user = userService.getById((long) id);
try {
userService.delete(user);
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "redirect:/admin/users/list.html";
}
// For add and update person both
@RequestMapping(value = "add" , method = RequestMethod.POST)
public String addPerson(@ModelAttribute("user") User user,
BindingResult result) {
if (result.hasErrors()) {
return "error";
}
try {
if (user.getId() == 0) {
// new person, add it
this.userService.create(user);
} else {
// existing person, call update
this.userService.saveOrUpdate(user);
}
} catch (ServiceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "redirect:/admin/users/list.html";
}
@RequestMapping(value = "edit/{id}" )
public String editPerson(@PathVariable("id") int id , Model model) {
// Prepare Groups
List<Group> groups = groupService.list();
List<String> groupList = new ArrayList<String>();
for (Group group : groups) {
groupList.add(group.getGroupName());
}
model.addAttribute("groupList", groupList);
model.addAttribute("user", this.userService.getById((long) id));
model.addAttribute("users", this.userService.list());
return "admin/userAdmin";
}
}
问题是当我点击编辑 link 时,表单由项目信息正确填充,因此用户可以编辑检索到的数据,但是对象 "user" 从方法 [=38] 检索=] 在控制器中的 "addPerson" 方法中(
代码行:model.addAttribute("user", this.userService.getById((long) id));在 editPerson 方法中) 让所有其他字段为空,因此当我合并数据时,保存操作失败。
示例:用户项目有一个其他字段 "AdminAPassword" 未在 JSP 中打印并且用户未更改,当从表单中检索数据时,该字段为空。
你能帮忙吗
提前致谢
你的问题有点不清楚,我会根据你的标题来处理。我的理解是,您希望在控制器内的方法之间共享 user bean。您可以通过使用 @SessionAttributes
@SessionAttributes("user")
@Controller
@RequestMapping(value = "/admin/users/")
public class UserController {
使用此设置,名称与 @SessionAttributes 中列出的属性匹配的所有模型属性将在后续请求中保留。您可以了解更多 here