4

我使用打印编写器直接在 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。

4

3 回答 3

1

也许应用服务器正在重置您的请求对象。您可以通过创建一个新的请求对象来解决此问题,该对象包装您的原始请求,并将其传递给请求调度程序。

例如 MyHttpRequest myRequest = new MyHttpRequest(req); myRequest.setAttribute(...); req.getRequestDispatcher("index.jsp").forward(myRequest, resp);

和 MyHttpReqest 代码:

   class MyHttpRequest extends HttpServletRequestWrapper
   {
      Map attributes = new HashMap();
      MyHttpRequest(HttpRequest original) {
         super(original);
      }
      @Override
      public void setAttribute(Object key, Object value) {
          attributes.put(key, value);
      }

      public Object getAttribute(Object key) {
          Object value = attributes.get(key);
          if (value==null)
              value = super.getAttribute(key);
          return value;
      }

      // similar for removeAttribute 
   }
于 2010-05-17T07:59:57.983 回答
1

我认为这取决于网络服务器。但是在不改变你以前的目录结构的情况下,

尝试像这样将列表放入会话中

req.getSession(false).setAttribute("artists", artists);

在你的jsp中,

List<Artist> artists = (List<Artist>) request.getSession(false).getAttribute("artists"); 

我认为我的方法适用于所有 Web 服务器。

于 2010-05-17T10:59:19.490 回答
0

我只是在尝试修复 WebContent/ 中的目录结构时无意中发现

我之前的目录结构是

WEB-CONTENT/
    - META-INF/
    - WEB-INF/
    index.jsp

然后我尝试在 WEB-CONTENT 中创建一个文件夹 jsp 并将 index.jsp 放在那里。有用!

我现在的目录结构是

WEB-CONTENT/
    - META-INF/
    - WEB-INF/
    - jsp/
        -index.jsp

我不知道为什么它有效,但它确实有效。

这里有人知道为什么吗?

于 2010-05-17T09:15:02.600 回答