4

印刷ライターを使用してサーブレットでリストを直接印刷すると、リストが印刷されます。

ただし、jsp を挿入しようとすると、JSTL を使用するかスクリプトレットを使用するかにかかわらず、リストが出力されません。

オブジェクトがnullであるかどうかをJSTLとスクリプトレットでテストしようとしましたが、そうであることがわかりました!

これはなぜ起こり、どうすれば修正できますか?

動作するサーブレット コード

for (Artist artist:artists){
    resp.getWriter().println(artist.getName());
}

オブジェクトをリクエストに入れるサーブレット コード

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 を突然検出するスクリプトレット コード

<% 

    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);

そして MyHttpRequest コード:

   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

Webサーバーに依存すると思います。ただし、以前のディレクトリ構造を変更しなくても、

このようにリストをセッションに入れてみてください

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 に答える