簡體   English   中英

HttpServletRequest中突然缺少對象

[英]Object suddenly missing from HttpServletRequest

我使用打印編寫器直接在servlet中打印列表,然后打印列表。

但是,當我嘗試放入jsp時,無論使用JSTL還是scriptlet,列表都不會打印。

我嘗試在JSTL和scriptlet中測試對象是否為null,結果是!

為什么會發生這種情況,我該如何解決?

有效的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。

也許應用服務器正在重置您的請求對象。 您可以通過創建一個新的請求對象來解決此問題,該對象包裝原始請求,然后將其傳遞給請求分配器。

例如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 
   }

我認為這取決於Web服務器。 但無需更改您以前的目錄結構,

嘗試像這樣將列表放入會話中

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

在你的jsp中

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

我認為我的方法適用於所有Web服務器。

我只是在嘗試修復WebContent /中的目錄結構時無意間發現了

我以前的目錄結構是

網頁內容/
-META-INF /
-WEB-INF /
index.jsp

然后,我嘗試在WEB-CONTENT中創建一個文件夾jsp,並將index.jsp放在此處。 有用!

我當前的目錄結構是

網頁內容/
-META-INF /
-WEB-INF /
-jsp /
-index.jsp

我不知道為什么會這樣,但是確實可以。

有人知道為什么嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM