【发布时间】:2013-12-31 20:15:29
【问题描述】:
嗯,这个错误肯定是由于我犯了某种错误造成的。下面是我的代码。
小服务程序:
package Servlets;
// import statements
public class AdminResource extends HttpServlet {
List<userList> users = new ArrayList<>();
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Database db = (Database) getServletContext().getAttribute("db");
String sql = "select * from TAHMID_NIPS.GROUPS";
ResultSet rs;
try {
rs = db.runSql(sql);
// int i = 0;
while (rs.next()) {
userList user = new userList(rs.getString("USERNAME"), rs.getString("GROUPID"));
users.add(user);
/* used a printWriter here to access the bean in the servlet
out.println(users.get(i).getUserName());
out.println(users.get(i).getGroupID());
i++;
*/
}
request.setAttribute("users", users);
request.getRequestDispatcher("userList.jsp").forward(request, response);
} catch(SQLException ex){}
}
// doGet(), doPost(), getServletInfo() methods..
}
JavaBean 类::
public class userList {
private String GroupID;
private String UserName;
public userList(String GroupID, String UserName){
this.GroupID = GroupID;
this.UserName = UserName;
}
public String getGroupID() {
return GroupID;
}
public void setGroupID(String GroupID) {
this.GroupID = GroupID;
}
public String getUserName() {
return UserName;
}
public void setUserName(String UserName) {
this.UserName = UserName;
}
}
分派的JSP视图:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>These are the users in the database!</h1><br>
<c:forEach var="iterator" items="${users}">
<c:out value="${iterator.UserName}"/> <br>
</c:forEach>
</body>
</html>
在 web.xml 文件中声明了数据库 URL、密码和其他所需信息,并实现了 contextListener 类。当数据显示在 servlet 中时,该应用程序运行良好。但是由于我们是 MVC 粉丝,所以当我尝试使用 EL 访问 bean 时问题就开始了。无法访问这些字段。
关于数据库:
这是一个名为 Groups 的表,其中包含两个字段:UserName、GroupID。但是它们都没有显示在 JSP 视图中。
问题可能出现在 JSP 视图中的 EL 中。请高手帮忙。
【问题讨论】:
-
见similar question。实际上,您必须以某种方式(例如作为请求或会话属性)将 bean 传递给 JSP,然后才能在 EL 上调用它。另外,为了更好的安全性,最好使用JSTL 而不是普通的 EL。
-
让您的代码工作的最简单的方法是在您的 Servlet AdminResource 中更改一行。更改 model.list(context);到 request.setAttribute("users", model.list(context));
-
@t0mppa 我根据您提供的类似问题链接更改了 servlet 代码并删除了查询提供程序 java 类。然后我就能够使用 servlet 中的注释代码部分访问 servlet 中的 bean。但仍然无法获取在 JSP 中查看的记录。 JSP EL 中有相当于 users.get(i).getUserName() 的吗?或者我需要做任何修改吗?请帮忙。并感谢您提供的链接。至少现在我确信 bean 工作得很好。新年快乐..
-
您能否更改您的 bean 以符合 Java 命名标准,即类名
UserList和字段userName和groupID,然后将 EL 更改为${iterator.userName}?那么它应该被正确拾取。 -
所以您无法获取用户名,因为您忽略了命名标准?那是一些有趣的行为。很高兴知道。您应该将此作为答案@t0mppa。
标签: jsp jakarta-ee model-view-controller javabeans el