Java Jsp文件无法迭代servlet中的复杂元素
我正在尝试将一个posts容器从servlet传递到jsp,以便显示该jsp页面上的所有元素。每个元素都有时间、名称和内容属性。但是,jsp文件无法迭代这些元素。我怎样才能修好它 我有一门课:Java Jsp文件无法迭代servlet中的复杂元素,java,jsp,servlets,parameters,iterator,Java,Jsp,Servlets,Parameters,Iterator,我正在尝试将一个posts容器从servlet传递到jsp,以便显示该jsp页面上的所有元素。每个元素都有时间、名称和内容属性。但是,jsp文件无法迭代这些元素。我怎样才能修好它 我有一门课: public class post { public post(long time, String name, String content) { super(); this.time = time; this.name= name; this.content= conte
public class post {
public post(long time, String name, String content) {
super();
this.time = time;
this.name= name;
this.content= content;
}
public String name;
public String content;
public long time;
}
还有一个servlet,我在其中执行以下操作:
post[] messages;
messages = sortMessages(data); // construct array of post
for (int i = 0; i < messages.length; i++) {
request.setAttribute("posts", messages[i]);
}
通过这种方式发送包含所有值的列表对象,现在在jsp中,您可以使用此对象通过for循环获取所有值。<c:forEach var="message" items="${requestScope.posts}">
<c:out value="${message}"/>
</c:forEach>
通过这种方式发送包含所有值的列表对象,现在在jsp中,您可以使用此对象通过for循环获取所有值。<c:forEach var="message" items="${requestScope.posts}">
<c:out value="${message}"/>
</c:forEach>
通过以下方式更改它解决了iteratin问题:
request.setAttribute("posts", messages);
但是,我无法访问其字段并获取错误:
Property 'name' not found on type serv.post
通过以下方式对其进行更改,解决了iteratin问题:
request.setAttribute("posts", messages);
但是,我无法访问其字段并获取错误:
Property 'name' not found on type serv.post
的items
属性期望集合类型对象能够对其进行迭代。但是在servlet中,您将posts
属性设置为post
对象的类型。不要将posts
属性设置为messages[i]
,只需将其设置为messages
。在servlet中不需要for循环
post[] messages;
messages = sortMessages(data); // construct array of post
request.setAttribute("posts", messages);
为了使您能够在JSP中打印post
对象的属性,您需要提供getter方法
public class post {
public Post(long time, String name, String content) {
super();
this.time = time;
this.name = name;
this.content = content;
}
public String name;
public String content;
public long time;
public String getName() {
return name;
}
public String getContent() {
return content;
}
public long getTime() {
return time;
}
}
的items
属性期望集合类型对象能够对其进行迭代。但是在servlet中,您将posts
属性设置为post
对象的类型。不要将posts
属性设置为messages[i]
,只需将其设置为messages
。在servlet中不需要for循环
post[] messages;
messages = sortMessages(data); // construct array of post
request.setAttribute("posts", messages);
为了使您能够在JSP中打印post
对象的属性,您需要提供getter方法
public class post {
public Post(long time, String name, String content) {
super();
this.time = time;
this.name = name;
this.content = content;
}
public String name;
public String content;
public long time;
public String getName() {
return name;
}
public String getContent() {
return content;
}
public long getTime() {
return time;
}
}
谢谢,这就是问题所在。但我如何才能以这种方式访问消息的内部字段?什么是消息?它是一个字符串数组还是别的什么?我错过了那个类的getter和setter,谢谢你,这就是问题所在。但我如何才能以这种方式访问消息的内部字段?什么是消息?它是字符串数组还是其他什么?我错过了那个类的getter和setter,谢谢