我自己完成一个项目,该项目的重点是用Java创建一个rest API,并使用JDBC从数据库中获取数据。问题是当我建立连接并使用main方法检索数据时,一切正常,但是当我尝试通过get请求检索数据时,它返回一个空列表。这是终点
@Path("/users")
public class UserResource {
UserService userService = new UserService();
@GET
@Path("/all")
@Produces(MediaType.APPLICATION_JSON)
public Response getAllUsers() throws InterruptedException {
List<User> users = userService.getAllUsers();
GenericEntity<List<User>> wrapper = new GenericEntity<List<User>>(users) {
};
return Response.ok(wrapper).build();
}
}
这是使用JDBC连接到数据库的类
public class ConnectionJDBC {
private static String USERNAME = "root";
private static String PASSWORD = "root";
private static String CONSTRING = "jdbc:mysql://localhost:3306/";
private static String DATABASE = "users_db";
static Connection connection;
public ConnectionJDBC() {
}
public static Connection getConnectionToDB() {
try {
String url = CONSTRING + DATABASE;
connection = DriverManager.getConnection(url, USERNAME, PASSWORD);
if (connection != null) {
System.out.println("Connected");
} else {
System.out.println("Connection faild");
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Something went wrong before establishing the connection");
}
return connection;
}
public List<User> getUsers() {
connection = getConnectionToDB();
String query = "SELECT * FROM users_db.user_info;";
List<User> userListRetrived = new ArrayList<>();
try {
PreparedStatement statement = connection.prepareStatement(query);
ResultSet dataRetrieved = statement.executeQuery();
while (dataRetrieved.next()) {
User user = new User(dataRetrieved.getInt("id"),
dataRetrieved.getString(2),
dataRetrieved.getString(3));
userListRetrived.add(user);
return userListRetrived;
}
} catch (Exception e) {
e.printStackTrace();
System.err.println("Something went wrong when retriving the data");
}
return userListRetrived;
}
}
UserService类在这里
public class UserService {
private ConnectionJDBC connectionJDBC = new ConnectionJDBC();
public UserService() {
}
public List<User> getAllUsers() {
ConnectionJDBC connectionJDBC = new ConnectionJDBC();
List<User> usersList = connectionJDBC.getUsers();
return usersList;
}
}
用户类是普通的Java bean。感觉像是getUsers方法正在忽略从数据库中获取数据,而是返回实例化的空列表。我正在使用jersey并将项目部署在Glassfish上。 关于如何解决此问题或对此情况进行解释的任何线索?
非常感谢!
答案 0 :(得分:0)
您没有从userResource()类调用userService.getUsers()
方法。请按以下步骤更新userResource()
类中的代码
GenericEntity<List<User>> wrapper = new GenericEntity<List<User>>(userService.getUsers());