简体   繁体   中英

Java Servlet store users info into Java DB

I have write a java servlet to insert and display users info from database. I am inserting a photo to all users. The problem is when I want to display the byte array for the photos it displays just the first bytes eg: [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

Ok let me check i analize your code and saw the image, the image is correct because you are using

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

as you can see the var called bytes is this:

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

why is it getting [B@43809cd3 ? because the method toString is not overriding in byte.

What could you do? if your byte is not null then iterate it and make your own like this:

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

So now you will put byteAppender instead of bytes so this will be:

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

So your coude could be like this:

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


    }

Also you could read this: how to convert byte array to string and vice versa

Hope it help you.

Cya

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM