gpt4 book ai didi

java - 如何将数组列表从servlet传递到JSP?

转载 作者:行者123 更新时间:2023-11-30 02:46:22 25 4
gpt4 key购买 nike

在 servlet 中:

 List<myItem> yourObjectToReturn = search.parserContent();
request.setAttribute("yourObjectToReturn",yourObjectToReturn);

数组 yourObjectToReturn 包含 3 个变量(id、txtfile、sentence),您可以从中看到myItem 类

public class myItem{
String sentence;
int id;
String txtfile;

// public myItem(){
// }
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public String getTxtfile(){
return txtfile;
}
public void setTxtfile(String txtfile){
this.txtfile = txtfile;
}
public String getSentence(){
return sentence;
}
public void setSentence(String sentence){
this.sentence = sentence;
}

}

如何在JSP中分别显示id、txtfile、sentence?如何将数组列表从 servlet 传递到 JSP 。

JSP:如何编辑我的 JSP。我的 JSP 出现错误:

type safety: unchecked cast from objectto arraylist

<%@ page import="java.io.*" %>
<%@ page import="java.net.*" %>
<%@ page import="java.util.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<% List<myItem> myList = (ArrayList<myItem>) request.getAttribute("yourObjectToReturn"); %>

The search Result SENTENCE IS: <%=myList %> --%>

</body>
</html>

最佳答案

不要在 jsp 页面中使用 scriptlet。通过以下方式包含 JSTL 标准标记库:

<%@ taglib uri='http://java.sun.com/jsp/jstl/core' prefix='c'%>

然后在您的 JSP 中使用迭代标记:

<c:forEach items="${requestScope.yourObjectToReturn}" var="current">
<c:if test="${current.sentence== 'secret' }">
<h1>seeeeeeeeeecret revealed</h1>
</c:if>
</c:forEach>

地点:

${requestScope.yourObjectToReturn} is your collection object.

并且(在每次迭代期间):

${current} is your actual element.

如需进一步引用,请查看http://docs.oracle.com/javaee/5/tutorial/doc/bnahq.html

为了避免奇怪的错误:不要忘记导入 myItem 类(实际上应该是 MyItem,你...)

编辑:在深入研究 JSTL 之前,我建议您阅读 this other question 。特别关注所选答案,它提供了很好的见解。

关于java - 如何将数组列表从servlet传递到JSP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40080576/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com