我已经通过寄存器形式将一些用户详细信息存储到db(hibernate和spring)中。我想在一个单独的JSP页面中显示所有用户的用户详细信息。有人可以告诉我该怎么做吗?
以下是我的控制器代码
@Controller
public class RegisterController {
@Autowired
private UserDao userDao;
@RequestMapping(value = "/registerForm.htm", method = RequestMethod.GET)
public ModelAndView registerPage(ModelMap map) {
User user = new User();
map.addAttribute(user);
return new ModelAndView("registerForm", "command", user);
}
@RequestMapping(value = "/registerProcess.htm", method = RequestMethod.POST)
public ModelAndView registerUser(@ModelAttribute("user") User user, Model model) {
model.addAttribute("userName", user.getUserName());
model.addAttribute("password", user.getPassword());
model.addAttribute("emailId", user.getEmailId());
System.out.println("user is " + user);
System.out.println("userdao is" + userDao);
userDao.saveUser(user);
return new ModelAndView("registerProcess", "user", user);
}
}
public void saveUser(User user) {
Session session=getSessionFactory().openSession();
Transaction tx;
tx=session.beginTransaction();
session.persist(user);
tx.commit();
}
答案 0 :(得分:2)
您应该在GET请求中获取要向用户显示的元素。这涉及以下步骤:
基于您当前代码并假设存在某些方法的一个非常简单的示例:
@Controller
public class RegisterController {
@Autowired
private UserDao userDao;
@RequestMapping(value="/registerForm.htm",method=RequestMethod.GET)
public ModelAndView registerPage(ModelMap map){
User user=new User();
map.addAttribute(user);
return new ModelAndView("registerForm","command",user);
}
@RequestMapping(value="/registerProcess.htm",method=RequestMethod.POST)
public ModelAndView registerUser(@ModelAttribute("user") User user,Model model){
model.addAttribute("userName", user.getUserName());
model.addAttribute("password", user.getPassword());
model.addAttribute("emailId",user.getEmailId());
System.out.println("user is "+user);
System.out.println("userdao is"+userDao);
userDao.saveUser(user);
return new ModelAndView("registerProcess","user",user);
}
//this is the new method with proper mapping
@RequestMapping(value="/userList.htm", method=RequestMethod.GET)
public ModelAndView registerPage(ModelMap map) {
//this method should retrieve the data for all users
List<User> userList = userDao.getAllUsers();
map.addAttribute("userList", userList);
return new ModelAndView("userList", map);
}
}
然后,在userList.jsp中:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="en">
<head>
<title>User List</title>
</head>
<body>
List of users:
<br />
<table>
<c:forEach items="${userList}" var="user">
<tr>
<td>${user.userName}</user>
</tr>
</c:forEach>
</table>
</body>
</html>
请注意,这是如何执行此操作的一个非常基本的示例。代码可以大大改进。
更多信息:
答案 1 :(得分:0)
编写另一个方法来获取所有用户,然后将检索到的用户列表存储在模型对象中,然后使用JSP中的JSTL forEach标记显示用户,可以使用此链接查看数据的显示方式在JSP上使用JSTL forEach循环:JSP Errors in ForEach Loop