Search code examples
javaweb-servicesjax-rpc

returning multiple values in web service


I am designing a web-service using java and eclipse which returns the user details who are marked as customer in the database

I was successfully able to return details for a single user (as there was only one entry in the dB) with the following code:

public class GetData {

public LoginDetails getDetails(){    
    Connection conn;
    Statement stmt;
    ResultSet rs;

    try {
        LoginDetails lds=new LoginDetails();
        Class.forName(driver);
        conn=DriverManager.getConnection(url,username,password);
        stmt=conn.createStatement();
        String sql="select * from login where usertype='customer'";
        rs=stmt.executeQuery(sql);
        while(rs.next()){
            lds.setUsername(rs.getString(1));
            lds.setPassword(rs.getString(2));
            lds.setUsertype(rs.getString(3));
            lds.setActive(rs.getString(4));

        }
        return lds;
    } 
    catch(ClassNotFoundException c){
        c.printStackTrace();
    }
    catch (SQLException e) {
        e.printStackTrace();
    }

    return null;
}
}

What should I do if there are multiple values in dB matching the criteria and I want to display them all. Please advice.


Solution

  • Change your method signature to public LoginDetails[] getDetails()

    And extend your while loop as follows:

        Collection<LoginDetails> details = new ArrayList<LoginDetails>();
        while(rs.next()){
            LoginDetails lds=new LoginDetails();
            lds.setUsername(rs.getString(1));
            lds.setPassword(rs.getString(2));
            lds.setUsertype(rs.getString(3));
            lds.setActive(rs.getString(4));
            details.add(lds);
    
        }
        return details.toArray(new LoginDetails[0]);