我使用打印编写器直接在 servlet 中打印一个列表,然后打印列表。
当我尝试放入 jsp 时,无论我使用 JSTL 还是 scriptlet,列表都不会打印出来。
如果对象为空,我尝试在 JSTL 和 scriptlet 中进行测试,结果证明它是!
为什么会发生这种情况,我该如何解决?
有效的 Servlet 代码
for (Artist artist:artists){
resp.getWriter().println(artist.getName());
}
将对象放入请求中的 Servlet 代码
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
ApplicationContext ctx =
new ClassPathXmlApplicationContext("com/helloworld/beans/helloworld-context.xml");
ArtistDao artistDao = (ArtistDao) ctx.getBean("artistDao");
List<Artist> artists = null;
try {
artists = artistDao.getAll();
} catch (SQLException e) {
e.printStackTrace();
}
req.setAttribute("artists", artists);
try {
req.getRequestDispatcher("index.jsp").forward(req, resp);
} catch (ServletException e) {
e.printStackTrace();
}
突然发现对象为 null 的 scriptlet 代码
<%
List<Artist> artists = (List<Artist>) request.getAttribute("artists");
if (artists == null) {
out.println("artists null");
}
else {
for (Artist artist: artists){
out.println(artist.getName());
}
}
%>
甚至jstl代码似乎都同意
<c:if test="${artists eq null}">
Artists are null
</c:if>
<c:forEach var="artist" items="${artists}">
${artist.name}
</c:forEach>
对于我的应用程序,我使用的是 weblogic、spring 2.5.6 和 ibatis。