如何在JSP中显示对象的数据

我已经通过注册表将一些用户详细信息存储到db(hibernate和弹簧)中。我想在单独的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();

}

回答:

您应该获取要在GET请求中显示给用户的元素。这涉及以下步骤:

  • 具有正确的URL映射和视图以处理GET。
  • 在将预处理您的URL的方法中获取数据。
  • 存储数据以作为请求属性显示给用户。
  • 转到视图(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);

}

//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>

请注意,这是有关如何执行此操作的非常基本的示例。该代码可以大大改进。

以上是 如何在JSP中显示对象的数据 的全部内容, 来源链接: utcz.com/qa/426199.html

回到顶部