Java Servlet将用户信息存储到Java DB中

时间:2017-04-04 16:21:26

标签: java arrays image servlets

我编写了一个java servlet来插入和显示数据库中的用户信息。我正在向所有用户插入照片。问题是,当我想显示照片的字节数组时,它只显示第一个字节,例如:[B @ 43809cd3

private void doAddUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    InputStream inputStream = null;
    Part filePart = request.getPart("image");
         if (filePart != null) {
            // prints out some information for debugging
            System.out.println(filePart.getName());
            System.out.println(filePart.getSize());
            System.out.println(filePart.getContentType());
            // obtains input stream of the upload file
            inputStream = filePart.getInputStream();
        }

    String message = null;            
    try {
        // Register JDBC driver
        Class.forName("org.apache.derby.jdbc.ClientDriver");
        // Open a connection
        Connection conn = DriverManager.getConnection("jdbc:derby://127.0.0.1:1527/tutoriumDB", "db", "db");           
        // Execute SQL query
        PreparedStatement st= conn.prepareStatement("insert into users(ID,NAME,LAT,LONG,IMAGE) values(?,?,?,?,?)");                                 
        st.setString(1, request.getParameter("id1"));
        st.setString(2, request.getParameter("name"));
        st.setString(3, request.getParameter("lat"));
        st.setString(4, request.getParameter("long"));
         if (inputStream != null) {               
                //st.setBlob(5, inputStream);
                st.setBinaryStream(5, inputStream, (int)filePart.getSize());
        }
        int row = st.executeUpdate();
        if (row > 0) {
            message = "File uploaded and saved into database";
        }

        st.close();
        conn.close();

        try (PrintWriter out = response.getWriter()) {
                out.println("Der Benutzer mit der ID: " +request.getParameter("id1")+" und Name: " +
                    request.getParameter("name")+" wurde eingefuegt");
        }
    } catch (ClassNotFoundException | SQLException ex) {
        Logger.getLogger(TutServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
   // sets the message in request scope
    request.setAttribute("Message", message);
    // forwards to the message page
    getServletContext().getRequestDispatcher("/submit.jsp").forward(
            request, response);
}

private void getAllUsers(HttpServletRequest request, HttpServletResponse response) throws IOException
{

     try {
        // Register JDBC driver
        Class.forName("org.apache.derby.jdbc.ClientDriver");

        // Open a connection
        Connection conn = DriverManager.getConnection("jdbc:derby://127.0.0.1:1527/tutoriumDB", "db", "db");

        // Execute SQL query
        String sql = "SELECT * FROM users order by ID";
        Statement stmt = conn.createStatement();

        ResultSet rs = stmt.executeQuery(sql);
        byte[] imgData = null ;
        ArrayList<String> users = new ArrayList<String>();
        while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            double lat = rs.getDouble("lat");
            double longit = rs.getDouble("long");
            byte[] bytes = rs.getBytes("image");            
            users.add(id + ", " + name+ ", " +lat+ ", " +longit+ ", " +bytes);
        }

        stmt.close();
        conn.close();

        try (PrintWriter out = response.getWriter()) {
            for (String s : users)
            {
                out.println(s);
            }
        }
    } catch (ClassNotFoundException | SQLException ex) {
        Logger.getLogger(TutServlet.class.getName()).log(Level.SEVERE, null, ex);
    }


}

Result of getAllUser

1 个答案:

答案 0 :(得分:0)

好的,让我检查一下,我分析你的代码并看到图像,图像是正确的,因为你正在使用

users.add(id + ", " + name+ ", " +lat+ ", " +longit+ ", " +bytes);

正如你所看到的那样,var就是这个:

byte[] bytes = rs.getBytes("image");       

为什么会得到[B @ 43809cd3?因为toString方法没有覆盖在byte中。

你能做什么?如果你的字节不是null,那么迭代它并自己创建:

byte[] bytes = new byte[2];
bytes[0] = 1;
bytes[1] = 127;

System.out.println(bytes);
StringBuilder byteAppender = new StringBuilder("");
if(null != bytes){
    for(byte b: bytes){
        byteAppender.append(b);
    }
    System.out.println("Ok bites are " +byteAppender);
}

所以现在你将把byteAppender而不是字节放在一起,所以这将是:

users.add(id + ", " + name+ ", " +lat+ ", " +longit+ ", " +byteAppender );

所以你的想法可能是这样的:

private void getAllUsers(HttpServletRequest request, HttpServletResponse response) throws IOException
    {

         try {
            // Register JDBC driver
            Class.forName("org.apache.derby.jdbc.ClientDriver");

            // Open a connection
            Connection conn = DriverManager.getConnection("jdbc:derby://127.0.0.1:1527/tutoriumDB", "db", "db");

            // Execute SQL query
            String sql = "SELECT * FROM users order by ID";
            Statement stmt = conn.createStatement();

            ResultSet rs = stmt.executeQuery(sql);
            byte[] imgData = null ;
            ArrayList<String> users = new ArrayList<String>();
            StringBuilder byteAppender = new StringBuilder(""); //here is the String you will make
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                double lat = rs.getDouble("lat");
                double longit = rs.getDouble("long");
                byte[] bytes = rs.getBytes("image");    
                if(null != bytes){ //you ask the object is not null
                    for(byte b: bytes){ //you itarete it
                        byteAppender.append(b); //you add it
                    }
                }
                users.add(id + ", " + name+ ", " +lat+ ", " +longit+ ", " +byteAppender); //you put it
                byteAppender.setLength(0); //you restart it
            }

            stmt.close();
            conn.close();

            try (PrintWriter out = response.getWriter()) {
                for (String s : users)
                {
                    out.println(s);
                }
            }
        } catch (ClassNotFoundException | SQLException ex) {
            Logger.getLogger(TutServlet.class.getName()).log(Level.SEVERE, null, ex);
        }


    }

您也可以阅读:how to convert byte array to string and vice versa

希望对你有所帮助。