[英]SpringMVC jsp view req parameters
我正在做一个春季MVC项目。 我的Admin.jsp页面是:
<form:form action="/users" method="post" ModelAttribute="user">
<table border="1" >
<tr>
<td><a href="/findUserById"> Find a User</a></td>
</tr>
<tr>
<td><a href="/edit">Edit a User</a></td>
</tr>
<tr>
<td><a href="/update">Update a User</a></td>
</tr>
<tr>
<td><a href="/edit"> Delete a User</a></td>
</tr>
<tr>
<td><a href="users">List of all the Users</a></td>
</tr>
</table>
</form:form>
单击href =“ users”后,请求将发送到控制器:
@RequestMapping(value = "/users", method = RequestMethod.GET)
public String usersList(@ModelAttribute("user") User user, BindingResult result, Model model) {
List<User> userList = userService.listPersons();
// attribute goes to jsp
model.addAttribute("userList", userList);
// return users.jsp page
return "users";
}
我的users.jsp页面是:
<body>
<table>
<thead style="background: #fcf">
<tr>
<th>ID</th>
<th>Name</th>
<th>User Id</th>
<th>Email</th>
<th>Department</th>
<th>Role</th>
<th colspan="3"></th>
</tr>
</thead>
<c:forEach items="${userList}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.userId}</td>
<td>${user.email}</td>
<td>${user.department}</td>
<td>${user.role}</td>
<td><a href="<c:url value='/edit/${user.id}' />">Edit</a></td>
<td><a href="<c:url value='/delete/${user.id}' />">Delete</a></td>
<td><a href="<c:url value='/edit/${user.id}' />">Update</a></td>
</tr>
</c:forEach>
</table>
</body>
在users.jsp页面上,我为列表中的每个用户单击href编辑按钮,URL变为users / {id},控件转到控制器的方法,该方法编写为:
@RequestMapping("/edit/{id}")
public String editUser(@ModelAttribute("user") User user, Model model) {
User u= userService.findById(id);
user.setId(id);
// Delegate to userService for update
userService.update(user);
model.addAttribute("id", id);
model.addAttribute("userList", userList);
return "editedUser";
}
我不知道如何从users.jsp到控制器方法中获取用户的ID。 我的editedUser.jsp页面是:
<body>
<h1>Today on </h1> <%= new java.util.Date() %>
<p>You have edited the user with id ${user.id} with info: </p>
${userList}
<p>Return to <a href="login">Login Page</a></p>
</body>
DaoImpl是
@Repository
public class UserDaoImpl implements UserDao {
private static final Logger logger = LoggerFactory.getLogger(UserDaoImpl.class);
@Autowired
private SessionFactory sessionFactory;
public UserDaoImpl() { }
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public UserDaoImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
// ***********************save User*****************
@Transactional
public boolean save(User user) {
// Retrieve session from Hibernate
Session session = sessionFactory.getCurrentSession();
// save
session.save(user);
return true;
}
// **************update/edit******************
@Transactional
public User update(User user) {
// Retrieve session from Hibernate
Session session = this.sessionFactory.getCurrentSession();
// Retrieve existing person via id
User existingUser = (User) session.get(User.class, user.getId());
// Assign updated values to this person
existingUser.setName(user.getName());
existingUser.setEmail(existingUser.getEmail());
existingUser.setRole(existingUser.getRole());
existingUser.setDepartment(existingUser.getDepartment());
// update Use
session.update(user);
// return to jsp
return user;
}
// ***********find user by Id*************
public User findById(int id) {
// Retrieve session from Hibernate
Session session = this.sessionFactory.getCurrentSession();
// get user
User u = (User) session.get(User.class, new Integer(id));
return u;
}
// *************************List of User**************
@SuppressWarnings("unchecked")
@Transactional
public List<User> listPersons() {
Session session = this.sessionFactory.getCurrentSession();
List<User> personsList = session.createQuery("from User").list();
for (User u : personsList) {
logger.info("User List::" + u);
}
return personsList;
}
// *************************Delete a User**************
public User deleteById(int id) {
Session session = this.sessionFactory.getCurrentSession();
User u = (User) session.load(User.class, new Integer(id));
if (null != u) {
session.delete(u);
}
logger.info("Person deleted successfully, person details=" + u);
return u;
}
当我运行该应用程序时,所有页面都可以正常浏览,直至到达“用户页面”,但是当我单击users.jsp上的edit / update href时,我会从tomcat7的控制台上获得它:
Unresolved compilation problems: id cannot be resolved to a variable id cannot be resolved to a variable id cannot be resolved to a variable
我怎样才能将ID从users.jsp获取到控制器,哪里出了问题? 请提出建议。 任何类似的示例应用程序将不胜感激。 谢谢
您的问题出在控制器方法参数中。 尝试这个:
@RequestMapping("/edit/{id}")
public String editUser(@PathVariable("id") Integer id, Model model) {
Integer userId = id; // get your id passed from jsp
// do whatever with the id
// ...
}
假设您的id
属性是Integer
。
方法参数列表中的变量id与RequestMapping中的{id}匹配。
您可以在以下文档中找到有关如何处理路径变量的更多信息:
Spring MVC文档
@RequestMapping(value = "/users", method = RequestMethod.GET)
public String usersList(@ModelAttribute("user") User user, BindingResult result, Model model) {
List<User> userList = userService.listPersons();
// attribute goes to jsp
model.addAttribute("userList", userList);
// return users.jsp page
return "users";
}
@ModelAttribute(“ user”)当您将表单从jsp传递到控制器时,将使用用户用户。 您也使用了list方法。 这是不对的。 您甚至不需要它(@ModelAttribute(“ user”))将列表显示给用户。
您正在从服务中删除[List userList]并返回String。 这也是错误的。 您可以按原样返回列表。
正如injun.Y所指出的,您只需要一个来自JSP的整数值$ {user.id}。 您不可能期望整个JavaScript对象与[User]对象具有相同的getter和setter方法。
如果您真的不熟悉PathVariable,那么可以使用HttpServletRequest。
@RequestMapping("/edit")
public String editUser(HttpServletRequest req, Model model) {
String id = req.getParameter("id");
User u= userService.findById(id);
//do things here
}
尝试以下代码片段:
@RequestMapping("/edit/{id}",method=RequestMethod.GET)
public String editUser(@PathVariable("id") Integer id, Model model) {
model.addAttribute("user", userService.findById(id));
return "editedUser";
}
您只需要编辑页面上的user
属性。 在以上代码段中,我进行了如下更改:
RequestMethod
设置为GET
@PathVariable
而不是@ModelAttribute
,例如从<a>
标记中发送的仅是id
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.