0

私は、ユーザーログインを提供する必要がある割り当てに取り組んでいます。その後、ユーザーは画像をアップロードできるページに移動し、以前の画像と新しい画像のすべてが下の表に表示されます。だから私のアプリケーションの構造はこのようなものです...

(わかりやすくするために、ほとんどのコードをトリミングしました)

画像のアップロードと表示を可能にするJSPファイル

<p>Please select an image file to upload(Max file size 1 MB)</p>

<%
    Integer userId = 0;
    userId = (Integer) session.getAttribute("userId");
%>
<%
    String errorMessage = (String) request.getAttribute("error");
    if (errorMessage != null) {
        out.print("<h4> " + errorMessage + "</h4>");
    }
%>
<form action="imageupload" enctype="multipart/form-data" method="post">
    <br /> <input type="file" name="uploader" id="uploader" /> <br /> <br />
    <input type="submit" />&nbsp;&nbsp;&nbsp; <input type="button"
        value="clear" onClick="clear()" />


</form>
<br />
<h4>Uploaded Images</h4>
<br />
<table width="80%">
    <tr>
        <th>S No.</th>
        <th>Name</th>
        <th>size</th>
        <th>Preview</th>
        <th>Actions</th>
    </tr>
    <%
        UserImagesDAOImplementation userImages = new UserImagesDAOImplementation();

        List<Image> images = (List<Image>) userImages.getUserImages(userId);

        for (Image image : images) {
    %>
    <tr>
        <td><%=image.getSn()%></td>
        <td><%=image.getImageName()%></td>
        <td><%=image.getSize()%></td>
        <td><% session.setAttribute("image",image.getImage() ); %><img src="toimage" height="100px" width="100px" /></td>
        <td><img src="img/edit.png" />&nbsp;&nbsp;<img src="img/url.png" /></td>
    </tr>
    <%
        }
    %>
</table>
<br />
Total space used: <%= (userImages.getSizeUsage(userId)/1024) %> KB / 10 MB

画像を返す「toimage」サーブレット

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    HttpSession session = request.getSession();
    Byte[] image = (Byte[]) session.getAttribute("image");
    int len = image.length;
    byte[] imageData = new byte[len];

    for(int i=0; i < len; i++) {
        imageData[i] = image[i];
    }

    response.setContentType("image/jpg");
    response.getOutputStream().write(imageData);
    response.getOutputStream().flush();
    response.getOutputStream().close();

}

私の問題は、リストの最後の画像がすべてのテーブル行に表示され、他の画像をアップロードした後、その新しい画像がすべての行に表示されることです。

サイトのデザインにはあまり自信がありませんが、JSPを使用するのはこれが初めてです。後でさらにいくつかの操作を実行する必要があるため、JSP内に画像リストを取得することにしました。問題は、セッション変数を設定するか、最後に呼び出されるsrcサーブレットにあると思います。それが何であれ、誰かがこのデザインの典型的なイベントの流れを説明できますか?

編集:「toimage」サーブレット内にprintステートメントを配置すると、それが1回だけ呼び出されていることが証明されます。では、JSPループを作成して毎回画像srcを呼び出すにはどうすればよいですか?

4

1 に答える 1

2

単一のセッション属性を使用して、すべての画像を保存します。したがって、ループの最後に、このセッション属性には最後のものが含まれます。

セッションをまったく使用しないでください。代わりに、ID または名前、または画像を識別するものを URL パラメーターとして渡す必要があります。

<img src="toimage?imageId=<%= image.getId() %>" height="100px" width="100px" />

そして、サーブレットはこのパラメーターを使用して、どの画像をロードしてブラウザーに送信する必要があるかを判断する必要があります。

また、JSTL と EL を学びます。スクリプトレットは使用しないでください。

于 2013-02-12T12:14:59.250 に答える