我有一个jsp页面(例如,MyJspPage.jsp
)-
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<%
ArrayList<Person> ownerList = (ArrayList<Person>) request
.getAttribute("ownerList");
//set again ..
request.setAttribute("ownerList",ownerList) ;
%>
</head>
<body>
<%
//itr on all the persons ..;
for (Person person : ownerList) {
%>
// some HTML code..
<%
}
%>
<form action="servlet123" method="POST">
// some fields ..
<input type="submit" value="join" />
</form>
</body>
</html>
还有一个servlet-
@WebServlet("/servlet123")
public class servlet123 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// get the then set ..
ArrayList<Person> ownerList = (ArrayList<Person)request.getAttribute("ownerList");
request.setAttribute("ownerList", ownerList);
// forward to `MyJspPage.jsp`
dispather.forward(request, response);
}
}
首先,另一个servlet转发到
MyJspPage.jsp
,并且运行良好,然后MyJspPage.jsp
和servlet123
之间像乒乓球一样。问题是当第二次到达MyJspPage.jsp
时会引发异常-type Exception report
message java.lang.NullPointerException
description The server encountered an internal error (java.lang.NullPointerException) that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: java.lang.NullPointerException
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:549)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
应该注意的是,当我从MyJspPage.jsp省略for循环并将其更改为-
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<%
ArrayList<Person> ownerList = (ArrayList<Person>) request
.getAttribute("ownerList");
//set again ..
request.setAttribute("ownerList",ownerList) ;
%>
</head>
<body>
<form action="servlet123" method="POST">
// some fields ..
<input type="submit" value="join" />
</form>
</body>
</html>
MyJspPage.jsp
和servlet123
之间的所有关系都可以正常工作。 最佳答案
这是一种方法。
JSP代码如下
您可以在会话中进行如下设置,而不是在请求中再次设置arraylistsession.setAttribute("ownerList",ownerList) ;
您可以在for循环中使用arraylist之前检查它是否为null。
if (ownerList != null)
{
for (Person person : ownerList) {
%>
// some HTML code..
<%
}
}
%>
在servlet中,您可以将代码编写为
HttpSession session = request.getSession(false);
ArrayList<Person> ownerList = (ArrayList<Person)session.getAttribute("ownerList");
request.setAttribute("ownerList", ownerList);
session.setAttribute("ownerList", null); // toremove unnecessary code from the session
也可能有其他方法。这只是您选择的那个。