在MySQL请求中使用的response.getOutputStream在JSP中抛出IllegalStateException

时间:2012-05-10 11:51:59

标签: java mysql servlets outputstream illegalstateexception

我面临着我发现的奇怪问题。我正在尝试通过从MySQL服务器检索和显示数据来创建一个动态创建“论坛 - 线程”的网站。此数据可以有两种类型:纯文本或图像文件(存储为BLOB)。在测试时,我们在数据库中有3个条目 - 1个文本,1个图片,1个文本。我们使用JSP和servlet来检索和显示数据。文本条目写得很好,但是当试图显示图片时,我们继续从OutputStream实例获取IllegalStateExceptions - 即,它将运行代码,直到我们尝试实例化OutputStream,然后抛出异常。

我们认为它与多线程有关,但在尝试使用同步和特定的重入锁之后,我们仍然得到了异常。我应该提一下,如果我们尝试将代码的“get-image”部分作为单独的servlet而不是作为JSP的一部分运行,它就会很好地显示图像。

servlet代码如下所示:

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class listConversation
 */
@WebServlet("/ListConversation")
public class ListConversation extends HttpServlet
{

    @Override
    protected synchronized void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    {
        try
        {
            String connectionURL = [our database URL, username and password];
            String myDriver = "com.mysql.jdbc.Driver";

            Class.forName(myDriver).newInstance();

            Connection con = DriverManager.getConnection(connectionURL);

            Statement stmt = con.createStatement();

            ResultSet rs = stmt.executeQuery("SELECT ID, Content1 FROM Conversations WHERE ConversationID=587 ORDER BY Date ASC");

            res.setContentType("text/html");
            PrintWriter out = res.getWriter();

            out.print("<hr>");

            while (rs.next())
            {
                out.print("<b>Besked</b><br/>" + rs.getString("Content1") + "<br/><br/>");

                try {

                    System.out.println("Try-block started.");
                    Statement stmt2 = con.createStatement();
                    System.out.println("Statement created.");
                    ResultSet rs2 = stmt2.executeQuery("SELECT Content2 FROM Conversations WHERE ID = 4");
                    System.out.println("Statement executed.");
                    ServletOutputStream outStream = res.getOutputStream();
                    System.out.println("Outputstream initialized.");
                    Blob image;
                            if (rs2.next()) {
                                image = rs2.getBlob(1);
                                System.out.println("Image created.");
                            } else {
                                res.setContentType("text/html");
                                out.println("h4><font color='red'>image not found for given id</font></h4>");
                                        return;
                            }
                            res.setContentType("image/gif");
                            InputStream in = image.getBinaryStream();
                            int length = (int) image.length();
                            int bufferSize = 1024;
                            byte[] buffer = new byte[bufferSize];
                            System.out.println("Initializing...");
                            while ((length = in.read(buffer)) != -1) {
                                outStream.write(buffer, 0, length);
                            }
                            System.out.println("Image streamed.");
                            in.close();
                            stmt2.close();
                            rs2.close();
                            outStream.close();
                            System.out.println("Closing.");
                            out.flush();
                }
                catch(IllegalStateException e)
                {
                    System.out.println("Darn OutputStreams...");
                }
                catch (Exception e) {
                    res.setContentType("text/html");
                    out.println("<h4><font color='red'>Image Display Error=" + e.getMessage() +
                            "</font></h4>");
                    return;
                }

                out.print("<hr>");
            }

            stmt.close();
            con.close();

            }
        catch (SQLException e)
        {
            e.printStackTrace();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
    {
        doGet(req,res);
    }


}

控制台输出是:

Try-block started. 
Statement created. 
Statement executed.
Darn OutputStreams...

因为我们有三个ConversationID为587的条目.Content1是文本,Content2是BLOBS。

非常感谢任何想法或更正。谢谢:D

1 个答案:

答案 0 :(得分:0)

您无法在同一响应中调用response.getWriter()和response.getOutputStream()。电话

PrintWriter out = res.getWriter();
当你打电话

时,

已经“声明”了回复

ServletOutputStream outStream = res.getOutputStream();

你得到例外。